<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Jobs\SaveContractPdfController;
use App\Models\Common\Constant;
use App\Models\Helper\IdBuilder;
use App\Models\ResourceModel\AmazonPlaceOrderContract;
use App\Models\ResourceModel\AmazonPlaceOrderContractDetail;
use App\Models\ResourceModel\AmazonPlaceOrderDetailModel;
use App\Models\ResourceModel\AmazonPlaceOrderTaskModel;
use App\Models\ResourceModel\Company;
use App\Models\ResourceModel\CustomSkuModel;
use App\Models\ResourceModel\SpuModel;
use App\Models\ResourceModel\Suppliers;
use Illuminate\Support\Facades\DB;
use Monolog\Handler\IFTTTHandler;
use PHPExcel_Style_Alignment;

class AmazonPlaceOrderContractModel extends BaseModel
{
    protected $amazonPlaceOrderContractModel;
    protected $amazonPlaceOrderContractDetailModel;
    protected $amazonPlaceOrderTaskModel;
    protected $amazonPlaceOrderDetailModel;
    protected $suppliersModel;
    protected $companyModel;
    protected $customSkuModel;
    protected $spuModel;
    protected $idBuilder;
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->amazonPlaceOrderContractModel = new AmazonPlaceOrderContract();
        $this->amazonPlaceOrderContractDetailModel = new AmazonPlaceOrderContractDetail();
        $this->amazonPlaceOrderTaskModel = new AmazonPlaceOrderTaskModel();
        $this->amazonPlaceOrderDetailModel = new AmazonPlaceOrderDetailModel();
        $this->suppliersModel = new Suppliers();
        $this->companyModel = new Company();
        $this->customSkuModel = new CustomSkuModel();
        $this->spuModel = new SpuModel();
        $this->idBuilder = new IdBuilder();
    }

    public function saveAmazonPlaceOrderContract($params)
    {
        // 校验参数
        $params        = $this->_checkSaveAmazonPlaceOrderContractParams($params);
        $contractData  = [
            'total_count'               => $params['total_count'],
            'total_price'               => $params['total_price'],
            'report_date'               => $params['contract_delivery_date'] ?? null,
            'sign_date'                 => $params['contract_place_order_date'],
            'contract_type'             => $params['contract_type'],
            'spu_count'                 => $params['spu_count'],
            'supplier_short_name'       => $params['supplier_short_name'],
            'supplier_id'               => $params['supplier_id'] ,
            'delivery_memo'             => $params['delivery_memo'] ?? '',
            'maker_id'                  => $params['maker_id'],
            'input_user_id'             => $params['input_user_id'],
            'company_id'                => $params['company_id'] ?? 0,
            'company_name'              => $params['company_name'],
            'memo'                      => $params['memo'] ?? '',
            'delivery_location'         => $params['delivery_location'] ?? '', // 交货地点
            'signing_location'          => $params['signing_location'], // 签约地点
            'acceptance_criteria'       => $params['acceptance_criteria'] ?? '', // 验收标准
            'brand'                     => $params['brand'] ?? '', // 品牌
            'bind_place_ids'            => $params['bind_place_ids'], // 绑定的下单计划id
            'payment_information'       => json_encode($params['payment_information'] ?? []), // 款项信息 存json数组
            'payment_settlement_method' => $params['payment_settlement_method'] ?? '', // 货款结算方式
            'contract_terms'            => $params['contract_terms'] ?? '', // 合同条款
            'contract_class'            => $params['contract_class'],// 合同类别
            'file'                      => json_encode($params['file'] ?? []), // 附件
            'supplier_no'               => $params['supplier_no'],
            'contract_status'           => $params['contract_status'] ?? 0,
            'process_contract_no'   => $params['process_contract'] ?? '',
            'process_supplier_id'   => $params['process_supplier_id'] ?? 0,
            'process_supplier_name' => $params['process_supplier_name'] ?? '',
            'periodic_id' => $params['periodic_id'] ?? 0
        ];
        // 保存合同
        if (empty($params['id'] ?? 0)) {
            $createIdKey = Constant::CONTRACT_CLASS_CREATE_KEY[$params['contract_class']] ?? '';
            if (!empty($createIdKey)){
                $contractNo = $this->idBuilder->createId($createIdKey);
            }else{
                throw new \Exception('未定义的合同类别！');
            }
//            if ($params['contract_class'] == 1) {
//                // 系统自动生成合同号
//                $contractNo = $this->idBuilder->createId('AMAZON_PLACE_ORDER_CONTRACT_CODE_PUBLIC');
//            } elseif ($params['contract_class'] == 2) {
//                // 系统自动生成合同号
//                $contractNo = $this->idBuilder->createId('AMAZON_PLACE_ORDER_CONTRACT_CODE_QUICK_RETURN');
//            } elseif ($params['contract_class'] == 3) {
//                // 系统自动生成合同号
//                $contractNo = $this->idBuilder->createId('AMAZON_PLACE_ORDER_CONTRACT_PURCHASE');
//            } else {
//                throw new \Exception('未定义的合同类别！');
//            }
            $contractData['contract_no'] = $contractNo;
            $contractData['create_time'] = date('Y-m-d H:i:s', microtime(true));
            $contractId                  = DB::table('cloudhouse_contract_total')->insertGetId($contractData);
            if (empty($contractId)) {
                throw new \Exception('合同数据创建失败！');
            }
        } else {
            $contractMdl = DB::table('cloudhouse_contract_total')
                ->where('id', $params['id'])
                ->first();
            if (empty($contractMdl)) {
                throw new \Exception('未查询到该合同数据！');
            }
            if (!in_array($contractMdl->contract_status, [-2, -1, 0])) {
                throw new \Exception('该合同非草拟/撤销/被拒绝状态不予修改！');
            }
            $contractNo                 = $contractMdl->contract_no;
            $contractData['updated_at'] = date('Y-m-d H:i:s', microtime(true));

            $update = DB::table('cloudhouse_contract_total')
                ->where('id', $contractMdl->id)
                ->update($contractData);
            if (empty($update)) {
                throw new \Exception('合同数据更新失败！');
            }
            // 删除合同明细
            DB::table('cloudhouse_contract')->where('contract_no', $contractNo)->delete();
            DB::table('cloudhouse_custom_sku')->where('contract_no', $contractNo)->delete();
            // 删除票据绑定信息
            db::table('cloudhouse_contract_bill_bind')->where('contract_no', $contractNo)->delete();
        }
        // 保存cloudhouse_contract明细
        foreach ($params['spu_list'] as $item) {
            $save = [
                'spu'               => $item['spu'],
                'spu_id'            => $item['spu_id'],
                'title'             => $item['title'],
                'count'             => $item['count'],
                'one_price'         => $item['one_price'],
                'price'             => $item['price'],
                'report_date'       => $item['report_date'],
                'contract_no'       => $contractNo,
                'type'              => 1,
                'create_user'       => $params['input_user_id'],
                'sign_date'         => $params['contract_place_order_date'],
                'create_time'       => date('Y-m-d H:i:s', microtime(true)),
                'color_identifying' => $item['color_identifying'],
                'color_name'        => $item['color_name'],
                'order_id'          => $item['order_id'],
                'img'               => $item['img'] ?? '',
                'memo'              => $item['memo'] ?? '',
                'num_info' => $item['num_info'],
                'rule' => $item['rule'],
            ];
            $id   = DB::table('cloudhouse_contract')->insertGetId($save);
            if (empty($id)) {
                throw new \Exception('合同SPU明细数据创建失败！');
            }
        }
        // 保存cloudhouse_custom_sku明细
        foreach ($params['custom_sku_list'] as $item) {
            $save = [
                'spu'           => $item['spu'],
                'spu_id'        => $item['spu_id'],
                'custom_sku'    => $item['custom_sku'],
                'custom_sku_id' => $item['custom_sku_id'],
                'size'          => $item['size'],
                'num'           => $item['order_num'],
                'price'         => $item['price'],
                'contract_no'   => $contractNo,
                'color'         => $item['color_identifying'],
                'color_name'    => $item['color_name'],
                'color_name_en' => $item['color_name_en'],
                'name'          => $item['name'],
                'order_id'      => $item['order_id'],
                'sku'           => $item['sku'] ?? '',
                'sku_id'        => $item['sku_id'] ?? 0,
                'shop_id'       => $item['shop_id'] ?? 0,
                'fasin'         => $item['fasin'] ?? '',
                'fasin_code'    => $item['fasin_code'] ?? '',
            ];
//            if ($item['order_num'] <= 0){
//                continue;
//            }
            $id   = DB::table('cloudhouse_custom_sku')->insertGetId($save);
            if (empty($id)) {
                throw new \Exception('合同SPU明细数据创建失败！');
            }
        }
        // 释放下单详情
        $orderMdl = DB::table('amazon_place_order_detail')
            ->whereIn('order_id', explode(',', $params['bind_place_ids']))
            ->get();
        $orderList = [];
        foreach ($orderMdl as $order){
            $key = $order->order_id.'-'.$order->custom_sku_id;
            $orderNum = array_sum(json_decode($order->order_num));
            $orderList[$key] = [
                'order_num' => $orderNum,
                'is_contracted_num' => $order->is_contracted_num
            ];
        }
        foreach ($params['custom_sku_items'] as $_item) {
            $key = $_item['order_id'].'-'.$_item['custom_sku_id'];
            $order = $orderList[$key] ?? [];
            if (empty($order)){
                throw new \Exception('下单详情不存在！');
            }
            $isContractedNum = $order['is_contracted_num'] - $_item['num'];

            if ($isContractedNum >= $order['order_num']){
                $update = DB::table('amazon_place_order_detail')
                    ->where('order_id', $_item['order_id'])
                    ->where('custom_sku_id', $_item['custom_sku_id'])
                    ->update([
                        'is_contracted' => 1,
                        'is_contracted_num' => $isContractedNum
                    ]);
            }
            if($order['order_num'] > $isContractedNum){
                $update = DB::table('amazon_place_order_detail')
                    ->where('order_id', $_item['order_id'])
                    ->where('custom_sku_id', $_item['custom_sku_id'])
                    ->update([
                        'is_contracted' => 0,
                        'is_contracted_num' => $isContractedNum
                    ]);
            }
        }
        // 更新下单状态
        $planIds = explode(',', $params['bind_place_ids']);
        foreach ($planIds as $id) {
            $orderDetailMdl = DB::table('amazon_place_order_detail')
                ->where('order_id', $id)
                ->where('is_contracted', 0)
                ->first();
            if (empty($orderDetailMdl)) {
                DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 3]);
            } else {
                DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 5]);
            }
        }

        // 保存合同款项信息
        $paymentInformation = $params['payment_information'] ?? [];
        foreach ($paymentInformation as $item) {
            $save   = [
                'contract_no'        => $contractNo,
                'bill_type'          => $item['bill_type'],
                'ratio'              => $item['percentage'],
                'money'              => $item['money'],
                'application_reason' => $item['title'],
                'memo'               => $item['memo'] ?? '',
                'is_push'            => 0,
                'created_at'         => date('Y-m-d H:i:s'),
                'is_deleted'         => 0,
            ];
            $bindId = db::table('cloudhouse_contract_bill_bind')->insertGetId($save);
            if (empty($bindId)) {
                throw new \Exception('保存合同款项信息失败！');
            }
        }

        // 合同打印加入队列
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-服装范本（不含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 1,
            'contract_no' => $contractNo
        ];
        $job = new SaveContractPdfController();
        $job::runJob($data);
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-铁艺范本（不含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 2,
            'contract_no' => $contractNo
        ];
        $job::runJob($data);
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-服装范本（含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 3,
            'contract_no' => $contractNo
        ];
        $job::runJob($data);
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-铁艺范本（含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 4,
            'contract_no' => $contractNo
        ];
        $job::runJob($data);
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-卖单现货范本（不含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 5,
            'contract_no' => $contractNo
        ];
        $job::runJob($data);
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-卖单现货范本（含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 6,
            'contract_no' => $contractNo
        ];
        $job::runJob($data);
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-众拓范本（不含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 7,
            'contract_no' => $contractNo
        ];
        $job::runJob($data);
        $data = [
            'title' => '购销合同'.$contractNo,
            'type' => '购销合同-众拓范本（含税）-打印',
            'user_id' => $params['input_user_id'],
            'print_type' => 8,
            'contract_no' => $contractNo
        ];
        $job::runJob($data);

        return $contractNo;
    }

    public function _checkSaveAmazonPlaceOrderContractParams($params)
    {
        // 合同类型
        if (!isset($params['contract_type']) || empty($params['contract_type'])){
            throw new \Exception('合同类型有误或未设置！');
        }
        // 合同分类
        if (!isset($params['contract_class']) || empty(Constant::CONTRACT_CLASS[$params['contract_class']] ?? '')){
            throw new \Exception('合同分类未设置！');
        }else{
            if ($params['contract_class'] == 5){
                if (!isset($params['process_contract']) || empty($params['process_contract'])) {
                    throw new \Exception('未填写加工合同号！');
                }
                if (!isset($params['process_supplier_id']) || empty($params['process_supplier_id'])) {
                    throw new \Exception('未填写加工合同号！');
                }
                $supplierMdl = DB::table('suppliers')->where('Id', $params['process_supplier_id'])->first();
                if (empty($supplierMdl)){
                    throw new \Exception('未查询到该供应商信息！');
                }
                $params['process_supplier_name'] = $supplierMdl->name;
            }
        }
        // 下合同日期
        if (!isset($params['contract_place_order_date']) || empty($params['contract_place_order_date'])){
            throw new \Exception('未选择合同签约日期！');
        }
        // 合同明细
        if (!isset($params['contract_items']) || empty($params['contract_items'])){
            throw new \Exception('未选择商品信息！');
        }

        // 公司抬头
        if (!isset($params['company_id']) || empty($params['company_id'])){
            throw new \Exception('未给定公司抬头标识！');
        }else{
            $company = db::table('company')->where('id', $params['company_id'])->first();
            if (empty($company)){
                throw new \Exception('公司抬头信息不存在！');
            }
            $params['company_name'] = $company->company_name;
        }
//        // 交货地点
//        if (!isset($params['delivery_location']) || empty($params['delivery_location'])){
//            throw new \Exception('未给定交货地点！');
//        }
        // 签约地点
        if (!isset($params['signing_location']) || empty($params['signing_location'])){
            throw new \Exception('未给定签约地点！');
        }
        // 经办人
        if (!isset($params['maker_id']) || empty($params['maker_id'])){
            throw new \Exception('未给定经办人！');
        }
        // 录入人
        if (!isset($params['input_user_id']) || empty($params['input_user_id'])){
            throw new \Exception('未给定录入人！');
        }
        // 合同总数量
        if (!isset($params['total_num']) || empty($params['total_num'])){
            throw new \Exception('未给定合同总数量！');
        }
        // 合同总额
        if (!isset($params['contract_total_amount']) || empty($params['contract_total_amount'])){
            throw new \Exception('未给定合同总额！');
        }
        // 合同明细
        if (isset($params['contract_items']) && !empty($params['contract_items'])){
            $itemsError = '';
            $items = $this->formatContractItems($params);
            $params['spu_list'] = $items['spu_list'];
            $params['custom_sku_list'] = $items['custom_sku_list'];
            $params['spu_count'] = $items['spu_count'];
            $params['custom_sku_items'] = $items['custom_sku_items'];
            $params['total_count'] = $items['contract_total_num'];
            $params['total_price'] = $items['contract_total_amount'];
        }else{
            throw new \Exception('请选择合同明细！');
        }

        // 供应商
        if (!isset($params['supplier_id']) || empty($params['supplier_id'])){
            throw new \Exception('未给定供应商标识！');
        }else{
            $supplier = DB::table('suppliers')->where('Id', $params['supplier_id'])->first();
            if (empty($supplier)){
                throw new \Exception('未查询到该供应商信息！');
            }
            if ($params['contract_class'] == 5){
                if (!in_array($supplier->name, ['厦门巨帝工贸有限公司', '泉州市馨妙缘服饰有限公司'])){
                    throw new \Exception('供应商只能选择：厦门巨帝工贸有限公司/泉州市馨妙缘服饰有限公司');
                }
            }

            $params['supplier_short_name'] = $supplier->name;//没有简称填写供应商名称
            $params['supplier_no'] = $supplier->supplier_no;
        }

        if (in_array($params['contract_class'], [1, 2])) {
            // 品牌
            if (!isset($params['brand']) || empty($params['brand'])){
                throw new \Exception('未选择品牌！');
            }

            // 合同交货日期
            if (!isset($params['contract_delivery_date']) || empty($params['contract_delivery_date'])){
                throw new \Exception('未选择合同交货日期！');
            }

            // 附件
            if (isset($params['file']) && !empty($params['file'])){
                $params['file'] = json_encode($params['file']);
            }
        }
        // 款项信息
        $params['contract_status'] = 0;
        if (isset($params['payment_information']) && !empty($params['payment_information'])){
            $error = '';
            $ratio = 0;
            foreach ($params['payment_information'] as $k => &$v){
                if (!isset($v['bill_type']) || empty($v['bill_type'])){
                    $error .= '请检查第'.($k+1).'行款项是否设置账款类型';
                }else{
                    if (!isset(Constant::BILL_TYPE[$v['bill_type']])){
                        $error .= '请检查第'.($k+1).'行款项设置的账款类型为非预设类型！';
                    }
                }
                if (!isset($v['percentage'])){
                    $error .= '请检查第'.($k+1).'行款项是否设置比率';
                }else{
                    if ($v['percentage'] <= 0){
                        $error .= '请检查第'.($k+1).'行款项比率数值是否正确';
                    }
                    $ratio += $v['percentage'];
                }
                if (!isset($v['title']) || empty($v['title'])){
                    $error .= '请填写第'.($k+1).'行申请事由！';
                }

                if ($v['percentage'] == 100 && $params['contract_class'] == 3 && $v['bill_type'] == 1){
                    $params['contract_status'] = 2;
                }

                $percentage = bcdiv($v['percentage'], '100', 8);
                $money = bcmul($percentage, $params['total_price'], 8);

                $v['money'] = $this->floorDecimal($money);
            }
            $contractTotal = array_sum(array_column($params['payment_information'], 'money'));
            if ($params['total_price'] < $contractTotal){
                throw new \Exception('款项信息有误，不可大于合同总额！款项总金额：'.$contractTotal.'；合同总金额：'.$params['total_price']);
            }
            if ($ratio != 100){
                throw new \Exception('比率设置总值不等于100%！');
            }
            if (!empty($error)){
                throw new \Exception('款项信息有误！'.$error);
            }
            $params['payment_information'] = $params['payment_information'];
        } else {
//                throw new \Exception('请填写款项信息有误！');
        }
        if (isset($params['periodic_id']) && isset(Constant::CONTRACT_PERIODIC_SETTLEMENT_METHOD[$params['periodic_id']])){
            $params['payment_settlement_method'] = Constant::CONTRACT_PERIODIC_SETTLEMENT_METHOD[$params['periodic_id']];
        }
        if (isset($params['bind_place_ids']) && !empty($params['bind_place_ids'])){
            $planIds = array_unique(explode(',', $params['bind_place_ids']));
            $params['bind_place_ids'] = implode(',', $planIds);
        }else{
            throw new \Exception('未给定绑定生产下单任务标识！');
        }

        return $params;
    }

    /**
     * @Desc:生产下单合同列表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/5/5 14:17
     */
    public function getAmazonPlaceOrderContractList($params)
    {
//        $startTime = microtime(true);
        $contractMdl = DB::table('cloudhouse_contract_total');
        if (!isset($params['user_id']) || empty($params['user_id'])){
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                $params['user_id'] = $users->Id ?? 0;
            }else{
                $params['user_id'] = 0;
            }
        }
        $controller = new Controller();
        $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['show_all_contract']]);

        if (!$power['show_all_contract'] && $params['contract_class'] != 3){
            $contractMdl = $contractMdl->where('input_user_id', $params['user_id']);
        }

        if (isset($params['contract_code']) && !empty($params['contract_code'])){
            $contractMdl = $contractMdl->where('contract_no', 'like', '%'.$params['contract_code'].'%');
        }
        if (isset($params['contract_type']) && !empty($params['contract_type'])){
            $contractMdl = $contractMdl->where('contract_type', $params['contract_type']);
        }
        if (isset($params['contract_class']) && !empty($params['contract_class'])){
            $contractMdl = $contractMdl->where('contract_class', $params['contract_class']);
        }
        if (isset($params['company_id']) && !empty($params['company_id'])){
            $contractMdl = $contractMdl->where('company_id', $params['company_id']);
        }
        if (isset($params['contract_status']) && !empty($params['contract_status'])){
            $contractMdl = $contractMdl->where('contract_status', $params['contract_status']);
        }
        if (isset($params['maker_id']) && !empty($params['maker_id'])){
            $contractMdl = $contractMdl->whereIn('maker_id', $params['maker_id']);
        }
        if (isset($params['input_user_id']) && !empty($params['input_user_id'])){
            $contractMdl = $contractMdl->whereIn('input_user_id', $params['input_user_id']);
        }
        if (isset($params['supplier_id']) && !empty($params['supplier_id'])){
            $contractMdl = $contractMdl->whereIn('supplier_id', $params['supplier_id']);
        }
        if (isset($params['sign_date']) && !empty($params['sign_date'])){
            $contractMdl = $contractMdl->whereBetween('create_time', $params['created_at']);
        }
        if (isset($params['report_date']) && !empty($params['report_date'])){
            $contractMdl = $contractMdl->whereBetween('report_date', $params['report_date']);
        }
        if (isset($params['organize_id']) && !empty($params['organize_id'])){
            $omMdl = db::table('organizes_member')->where('organize_id', $params['organize_id'])->get();
            $userIds = [];
            if ($omMdl->isNotEmpty()){
                $omMdl = $omMdl->toArrayList();
                $userIds = array_column($omMdl, 'user_id');
            }
            $placeMdl = db::table('amazon_place_order_task')
                ->whereIn('user_id', $userIds)
                ->get(['id']);
            $orderIds = [];
            if ($placeMdl->isNotEmpty()){
                $placeMdl = $placeMdl->toArrayList();
                $orderIds = array_column($placeMdl, 'id');
            }
            $contractMdl = $contractMdl->where(function($q) use ($orderIds){
                foreach ($orderIds as $orderId) {
                    $q->orWhere('bind_place_ids', 'like', '%'.$orderId.'%');
                }
                return $q;
            });
        }
        if (isset($params['is_purchase_order_no'])){
            if ($params['is_purchase_order_no'] == 1){
                $contractMdl = $contractMdl->where('purchase_order_no', '<>', '');
            }elseif($params['is_purchase_order_no'] == 0){
                $contractMdl = $contractMdl->where('purchase_order_no', '');
            }
        }
        if (isset($params['purchase_order_no'])){
            $contractMdl = $contractMdl->where('purchase_order_no', 'like', '%'.$params['purchase_order_no'].'%');
        }
        if (isset($params['order_id']) && !empty($params['order_id'])) {
            $contractMdl = $contractMdl->where('bind_place_ids', 'like', $params['order_id']);
        }
        if (isset($params['order_user_id'])){
            $orderMdl = db::table('amazon_place_order_task')
                ->whereIn('user_id', $params['order_user_id'])
                ->get(['id'])
                ->toArrayList();
            $orderIds = array_unique(array_column($orderMdl, 'id'));
            $contractMdl = $contractMdl->where(function ($q) use ($orderIds){
                foreach ($orderIds as $orderId) {
                    $q->orWhere('bind_place_ids', 'like', '%'.$orderId.'%');
                }
                return $q;
            });
        }
        if (isset($params['platform_id'])){
            $orderMdl = db::table('amazon_place_order_task')
                ->whereIn('platform_id', $params['platform_id'])
                ->get(['id'])
                ->toArrayList();
            $orderIds = array_unique(array_column($orderMdl, 'id'));
            $contractMdl = $contractMdl->where(function ($q) use ($orderIds){
                foreach ($orderIds as $orderId) {
                    $q->orWhere('bind_place_ids', 'like', '%'.$orderId.'%');
                }
                return $q;
            });
        }
        if (isset($params['logistics_code'])){
            $purchase = db::table('alibaba_order_item')
                ->where('logisticsBillNo', 'like', '%'.$params['logistics_code'].'%')
                ->get();
            $purchaseNos = [];
            if ($purchase->isNotEmpty()){
                $purchaseNos = array_column($purchase->toArrayList(), 'order_id');
            }
            $contractMdl = $contractMdl->whereIn('purchase_order_no', $purchaseNos);
        }
        if (isset($params['logisticsBillNo'])){
            $purchase = db::table('alibaba_order_item')
                ->where('logisticsBillNo', 'like', '%'.$params['logisticsBillNo'].'%')
                ->get();
            $purchaseNos = [];
            if ($purchase->isNotEmpty()){
                $purchaseNos = array_column($purchase->toArrayList(), 'order_id');
            }
            $contractMdl = $contractMdl->whereIn('purchase_order_no', $purchaseNos);
        }
        if (isset($params['spu'])){
            $spuMdl = db::table('self_spu')
                ->where('spu', 'like', '%'.$params['spu'].'%')
                ->orwhere('old_spu', 'like', '%'.$params['spu'].'%')
                ->get(['id'])
                ->toArrayList();
            $spuIds = array_column($spuMdl, 'id');
            $contractSpuMdl = db::table('cloudhouse_contract')
                ->whereIn('spu_id', $spuIds)
                ->get(['contract_no'])
                ->toArrayList();
            $contractNo = array_column($contractSpuMdl, 'contract_no');
            $contractMdl = $contractMdl->whereIn('contract_no', $contractNo);
        }

        $count = $contractMdl->count();
        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $offsetNum = $limit * ($page-1);
        $list = $contractMdl->limit($limit)
            ->orderBy('create_time', 'DESC')
            ->offset($offsetNum)
            ->get();
//        $suppliersMdl = $this->suppliersModel::query()
//            ->get();
//        $companyMdl = $this->companyModel::query()
//            ->get();

        $orderMdl = db::table('amazon_place_order_task')
            ->where('status', '>', 2)
            ->get(['id', 'user_id', 'platform_id'])
            ->keyBy('id');
        $organizeMdl = db::table('organizes_member as a')
            ->leftJoin('organizes as b', 'a.organize_id', '=', 'b.Id')
            ->get(['a.*', 'b.name as organize_name'])
            ->keyBy('user_id');
//        $userMdl = db::table('users')
//            ->get(['Id', 'account'])
//            ->keyBy('Id');

//        if ($params['token'] == '4E55F683DB24324A15B08F193312D3CD'){
//            $endTime = microtime(true);
//            $time = ($endTime - $startTime);
//            var_dump($time.'秒');exit();
//        }
        $platformMdl = db::table('platform')
            ->get(['Id', 'name'])
            ->keyBy('Id');
        $supplier = db::table('suppliers_auxiliary')
            ->get(['Id', 'url_dp'])
            ->keyBy('Id');

        $all_purchase_order_no = [];
        foreach ($list as $item){
//            foreach ($suppliersMdl as $sp){
//                if ($sp->Id == $item->supplier_id){
//                    $item->supplier_name = $sp->short_name ? $sp->short_name : $sp->name;
//                }
//            }
//            foreach ($companyMdl as $cy){
//                if ($cy->id == $item->company_id){
//                    $item->company_name = $cy->company_name ?? '';
//                }
//            }
            $maker = $this->GetUsers($item->maker_id);
            $inputUser = $this->GetUsers($item->input_user_id);
//            $item->suppliers_link = '';
//            $supplier = db::table('suppliers_auxiliary')->where('supplier_id',$item->supplier_id)->first();
//            if($supplier){
//                $item->suppliers_link = $supplier->url_dp;
//            }
            $item->suppliers_link = $supplier[$item->supplier_id]->url_dp ?? '';
            $item->maker_name = $maker['account'] ?? '';
            $item->input_user_name = $inputUser['account'] ?? '';
            $item->contract_type_name = $item->contract_type;
            $item->status_name = Constant::CONTRACT_STATUS[$item->contract_status] ?? '';
            $item->payment_information = json_decode($item->payment_information) ?? [];
            $item->payment_information = $item->payment_information ?? [];
            $item->contract_delivery_date = date('Y-m-d', strtotime($item->report_date)); // 合同交货日期
            $item->contract_place_order_date = date('Y-m-d', strtotime($item->sign_date)); // 下合同日期
            $item->supplier_name = $item->supplier_short_name ?? '';
            $item->contract_submit_date = $item->pursubmit_date;
            $item->contract_audit_date = $item->purend_date;
            $item->created_at = $item->create_time;
            $item->total_num = $item->total_count;
            $item->contract_total_amount = $item->total_price;
            $item->contract_code = $item->contract_no;
            $item->contract_class_name = Constant::CONTRACT_CLASS[$item->contract_class] ?? '';
            if(!empty($contractMdl->payment_information)){
                foreach ($contractMdl->payment_information as &$v){
                    $v['bill_type_name'] = Constant::BILL_TYPE[$v['bill_type'] ?? ''] ?? '';
                }
            }
            $orderIds = array_unique(explode(',', $item->bind_place_ids));
            $organizeNames = [];
            $bindOrder = [];
            $platformName = [];
            foreach ($orderIds as $orderId){
                $userId = $orderMdl[$orderId]->user_id ?? 0;
                $organizeName = $organizeMdl[$userId]->organize_name ?? '';
                if (!empty($organizeName)){
                    $organizeNames[] = $organizeName;
                }
                $userName = $this->GetUsers($userId)['account'] ?? '';
                $bindOrder[] = $orderId.'('.$userName.')';
                $platformId = $orderMdl[$orderId]->platfrom_id ?? 0;
                $platformName[] = $platformMdl[$platformId]->name ?? '';
            }
            $task_id = db::table('tasks')
                ->where('ext','like','%'.$item->contract_no.'%')
                ->where('class_id', 23)
                ->where('is_deleted', 0)
                ->first()
                ->Id ?? 0;
            $tasks_examine = db::table('tasks_examine')->where('task_id',$task_id)->get();
            //3已审核12未审核4已拒绝
            $examine_no = [];
            $examine_ok = [];
            $not_examine = [];
            if($tasks_examine->isNotEmpty()){
                foreach ($tasks_examine as $tv) {
                    # code...
                    if($tv->state==3){
                        //已审核
                        $examine_ok[$tv->user_id] = $this->GetUsers($tv->user_id)['account']??'';
                    }elseif($tv->state==4){
                        //已拒绝
                        $examine_no[$tv->user_id] = $this->GetUsers($tv->user_id)['account']??'';
                    }else{
                        //未审核
                        $not_examine[$tv->user_id] = $this->GetUsers($tv->user_id)['account']??'';
                    }
                }

            }
            $item->examine_no =  array_values($examine_no);
            $item->examine_ok =  array_values($examine_ok);
            $item->not_examine =  array_values($not_examine);

//            $item->task_id =  $task_id;
            $item->platform_name = implode(',', array_unique($platformName));
            $item->organize_name = implode(',', $organizeNames);
            $item->bind_place_ids = implode(',', $bindOrder);
            if (!empty($item->purchase_order_no)){
                $all_purchase_order_no[] = $item->purchase_order_no;
            }
            $item->file = json_decode($item->file, true) ?? [];

            if (in_array($item->contract_status, [2])){
                $item->pdf_file = json_decode($item->pdf_file, true) ?? [];
            }else{
                $item->pdf_file = [];
            }
            $item->payment_settlement_method = Constant::CONTRACT_PERIODIC_SETTLEMENT_METHOD[$item->periodic_id] ?? $item->payment_settlement_method;
        }

        $alibabaOrder = db::table('alibaba_order_item')
            ->whereIn('order_id', array_unique($all_purchase_order_no))
            ->get(['order_id', 'logisticsCode', 'logisticsBillNo'])
            ->keyBy('order_id');

        foreach ($list as $v){
            $v->logistics_code = $alibabaOrder[$v->purchase_order_no]->logisticsBillNo ?? '';
            $v->logisticsBillNo =  $alibabaOrder[$v->purchase_order_no]->logisticsBillNo ?? '';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }

    public function deleteAmazonPlaceOrderContract($params)
    {
        try {
//            throw new \Exception('删除功能暂时禁用！');
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('删除失败！未给定标识！');
            }
            $contractMdl = DB::table('cloudhouse_contract_total')
                ->whereIn('id', $params['id'])
                ->get();
            $error = '';
            DB::begintransaction();
            foreach ($contractMdl as $item){
                if (!in_array($item->contract_status, [0, -1, -2])){
                    $error .= $item->contract_no.'，';
                }
                // 恢复下单详情数据
                $orderMdl = db::table('amazon_place_order_detail')
                    ->whereIn('order_id', explode(',', $item->bind_place_ids))
                    ->get();
                $orderList = [];
                foreach ($orderMdl as $order){
                    $key = $order->order_id.'-'.$order->custom_sku_id;
                    $orderNum = array_sum(json_decode($order->order_num));
                    $orderList[$key] = [
                        'order_num' => $orderNum,
                        'is_contracted_num' => $order->is_contracted_num
                    ];
                }
                $contractCustomSkuMdl = DB::table('cloudhouse_custom_sku')->where('contract_no', $item->contract_no)->get();
                foreach ($contractCustomSkuMdl as $cSku){
                    $key = $cSku->order_id.'-'.$cSku->custom_sku_id;
                    if (isset($orderList[$key])){
                        $isContractedNum = $orderList[$key]['is_contracted_num'] - $cSku->num;
                        if ($isContractedNum < $orderList[$key]['order_num']){
                            $update = DB::table('amazon_place_order_detail')
                                ->where('order_id', $cSku->order_id)
                                ->where('custom_sku_id', $cSku->custom_sku_id)
                                ->update([
                                    'is_contracted' => 0,
                                    'is_contracted_num' => $isContractedNum
                                ]);
                        }else{
                            $update = DB::table('amazon_place_order_detail')
                                ->where('order_id', $cSku->order_id)
                                ->where('custom_sku_id', $cSku->custom_sku_id)
                                ->update([
                                    'is_contracted' => 1,
                                    'is_contracted_num' => $isContractedNum
                                ]);
                        }
                    }
                }
            }
            if (!empty($error)){
                throw new \Exception("删除失败！合同号：".$error.'非 审核被拒绝/退回/草拟 状态，不予删除！');
            }

            $contractMdl = $contractMdl->toArrayList();
            $contractNos = array_column($contractMdl, 'contract_no');

            // 删除合同
            $delete = DB::table('cloudhouse_contract_total')
                ->whereIn('id', $params['id'])
                ->delete();
            // 删除合同spu数据
            $contractSpuMdl = DB::table('cloudhouse_contract')
                ->whereIn('contract_no', $contractNos)
                ->get();
            DB::table('cloudhouse_contract')
                ->whereIn('contract_no', $contractNos)
                ->delete();
            // 删除合同库存sku数据
            DB::table('cloudhouse_custom_sku')
                ->whereIn('contract_no', $contractNos)
                ->delete();
            // 更新下单任务状态
            $placeIdsArr = array_column($contractMdl, 'bind_place_ids');
            $placeIds = [];
            foreach ($placeIdsArr as $item){
                $placeIds = array_merge($placeIds, explode(',', $item));
            }
            $placeIds = array_unique($placeIds);
            foreach ($placeIds as $id){
                $orderDetailMdl = DB::table('amazon_place_order_detail')
                    ->where('order_id', $id)
                    ->where('is_contracted', 1)
                    ->first();
                if (empty($orderDetailMdl)){
                    $placeOrder = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 2]);
                }else{
                    $placeOrder = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 5]);
                }

            }
            // 删除合同的审核任务
            foreach ($contractMdl as $item){
                $taskDelete = DB::table('tasks')->where('ext', 'like', '%contract_no='.$item['contract_no'].'%')->delete();
                // 删除合同票据绑定数据
                db::table('cloudhouse_contract_bill_bind')
                    ->where('contract_no', $item['contract_no'])
                    ->delete();
            }

            DB::commit();
            return ['code' => 200, 'msg' => '删除成功！已删除'.$delete.'条合同数据！', 'data' => ['contract' => $contractMdl, 'contract_spu' => $contractSpuMdl, 'contract_custom_sku' => $contractCustomSkuMdl]];
        }catch (\Exception $e){
            DB::rollback();
            return ['code' => 500, 'msg' => '删除失败！原因：'.$e->getMessage().'; '.$e->getLine()];
        }
    }

    /**
     * @Desc:获取合同详情
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/5/23 10:39
     */
    public function getAmazonPlaceOrderContractDetail($params)
    {
        try {
            if (!isset($params['contract_no']) || empty($params['contract_no'])){
                throw new \Exception('未给定合同号！');
            }

            //导出
            if(isset($params['posttype'])){
                if($params['posttype']==2){
                    $cloud_model = new \App\Models\CloudHouse();
                    return $cloud_model->ContractListNew(['posttype'=>2,'find_user_id'=>$params['find_user_id'],'contract_no'=>$params['contract_no']]);
                }
            }

            $contractMdl = DB::table('cloudhouse_contract_total')
                ->where('contract_no', $params['contract_no'])
                ->first();
            if (empty($contractMdl)){
                throw new \Exception('未查询到该合同的信息！');
            }
            $suppliersMdl = db::table('suppliers')
                ->where('Id', $contractMdl->supplier_id)
                ->first();
            $companyMdl = db::table('company')
                ->where('id', $contractMdl->company_id)
                ->first();
            $payee = $suppliersMdl->payee ?? '';
            if (!empty($payee)){
                $payee = '('.$payee.')';
            }

            $contractMdl->supplier_name = $suppliersMdl->name ?? $contractMdl->supplier_short_name;
            if($contractMdl->supplier_id==227){
                $contractMdl->supplier_name = $suppliersMdl->name.'（简文镇）';
            }

            $contractMdl->company_name = $companyMdl->company_name ?? $contractMdl->company_name;
            $contractMdl->supplier_address = $suppliersMdl->supplier_address ?? '';
            $contractMdl->company_address = $contractMdl->address ?? '';
            $contractMdl->total_num = $contractMdl->total_count;
            $contractMdl->contract_total_amount = $this->floorDecimal($contractMdl->total_price);
            $contractMdl->created_at = $contractMdl->create_time;
            $contractMdl->updated_at = $contractMdl->updated_at ?? '';
            $contractMdl->contract_code = $contractMdl->contract_no;
            $maker = $this->GetUsers($contractMdl->maker_id);
            $inputUser = $this->GetUsers($contractMdl->input_user_id);
            $contractMdl->maker_name = $maker['account'] ?? ''; // 经办人名称
            $contractMdl->input_user_name = $inputUser['account'] ?? ''; // 录入人名称
            $contractMdl->contract_type_name = $contractMdl->contract_type; // 合同类型
            $contractMdl->status_name = Constant::CONTRACT_STATUS[$contractMdl->contract_status] ?? ''; // 合同状态
            $contractMdl->payment_information = json_decode($contractMdl->payment_information, true) ?? []; // 款项信息
            $contractMdl->process_contract = $contractMdl->process_contract_no;
            if (in_array($contractMdl->contract_status, [2])){
                $contractMdl->pdf_file = json_decode($contractMdl->pdf_file, true) ?? [];
            }else{
                $contractMdl->pdf_file = [];
            }
            foreach ($contractMdl->payment_information as &$_v){
                $_v['bill_type'] = (int)$_v['bill_type'];
            }
            foreach ($contractMdl->payment_information as &$v){
                $v['bill_type_name'] = Constant::BILL_TYPE[$v['bill_type'] ?? ''] ?? '';
            }
            $contractMdl->contract_delivery_date = date('Y-m-d', strtotime($contractMdl->report_date)); // 合同交货日期
            $contractMdl->contract_place_order_date = date('Y-m-d', strtotime($contractMdl->sign_date)); // 下合同日期
            $contractMdl->contract_class_name = Constant::CONTRACT_CLASS[$contractMdl->contract_class] ?? '';
            $contractMdl->file = json_decode($contractMdl->file, true) ?? []; // 文件
            $contractMdl->payment_settlement_method = Constant::CONTRACT_PERIODIC_SETTLEMENT_METHOD[$contractMdl->periodic_id] ?? $contractMdl->payment_settlement_method;
            $orderIds = array_unique(explode(',', $contractMdl->bind_place_ids));
            $orderTask = db::table('amazon_place_order_task as a')
                ->leftJoin('platform as b', 'a.platform_id', '=', 'b.Id')
                ->leftJoin('shop as c', 'a.shop_id', '=', 'c.Id')
                ->whereIn('a.id', $orderIds)
                ->get(['a.id', 'b.name as platform_name', 'c.shop_name']);
            $platformName = [];
            foreach ($orderTask as $order){
                $platformName[] = $order->platform_name.'-'.$order->shop_name;
            }
            $contractMdl->platform_name = implode(',', array_unique($platformName));

            $cloudhouseCustomSku = DB::table('cloudhouse_custom_sku')->where('contract_no', $contractMdl->contract_no)->get();
            $spuMdl = db::table('self_spu')->get();
            $spu = [];
            foreach ($spuMdl as $item){
                $spu[$item->id] = $item->content ?? '';
            }
            $customSkuMdl = db::table('self_custom_sku')
                ->get()
                ->keyBy('id');
            $customSkuItems = [];
            $rule = [];
            $sizeList = [];
            $imgMdl = db::table('self_spu_color')
                ->get();

            foreach ($cloudhouseCustomSku as $item){
                $customSkuItems[] = [
                    'id' => $item->id,
                    'contract_no' => $item->contract_no,
                    'spu_id' => $item->spu_id,
                    'custom_sku_id' => $item->custom_sku_id,
                    'spu' => $item->spu,
                    'custom_sku' => $item->custom_sku,
                    'color_name' => $item->color_name,
                    'color_name_en' => $item->color_name_en ?? '',
                    'color_identifying' => $item->color,
                    'size' => $item->size,
                    'order_id' => $item->order_id,
                    'order_num' => $item->num,
                    'name' => $customSkuMdl[$item->custom_sku_id]->name ?? '',
                    'name_en' => $customSkuMdl[$item->custom_sku_id]->name ?? '',
                    'delivery_date' => $item->delivery_date ?? $contractMdl->report_date,
                    'price' => $item->price,
                    'total_amount' => $this->floorDecimal($item->num * $item->price),
                    'img' => $this->GetCustomskuImg($item->custom_sku),
                    'sku' => $item->sku ?? '',
                    'sku_id' => $item->sku_id ?? 0,
                    'shop_id' => $item->shop_id ?? 0,
                    'fasin' => $item->fasin ?? '',
                    'fasin_code' => $item->fasin_code ?? '',
                    'suppliers_name' => $contractMdl->supplier_name,
                    'suppliers_id' => $contractMdl->supplier_id
                ];
                if (!in_array($item->size, $rule)){
                    $rule[] = $item->size;
                    $sizeList[$item->size] = $item->size;
                }
            }
            if (isset($params['is_update']) && $params['is_update'] == 1){
                $cloudhouseContract = DB::table('cloudhouse_contract')->where('contract_no', $contractMdl->contract_no)->get();
                $cloudhouseContract = json_decode(json_encode($cloudhouseContract), true);
                $spuItems = [];
                foreach ($cloudhouseContract as &$item){
                    $customSkuList = [];

                    foreach ($customSkuItems as $cus){
                        if ($cus['color_identifying'] == $item['color_identifying'] && $cus['order_id'] == $item['order_id'] && $cus['spu_id'] == $item['spu_id']){
                            $customSkuList[] = [
                                'spu_id' => $cus['spu_id'],
                                'custom_sku_id' => $cus['custom_sku_id'],
                                'spu' => $cus['spu'],
                                'custom_sku' => $cus['custom_sku'],
                                'color_name' => $cus['color_name'],
                                'color_name_en' => $cus['color_name_en'],
                                'color_identifying' => $cus['color_identifying'],
                                'size' => $cus['size'],
                                'order_num' => $cus['order_num'],
                                'name' => $customSkuMdl[$cus['custom_sku_id']]->name ?? '',
                                'delivery_date' => $item['report_date'],
                                'price' => $cus['price'],
                                'img' => $cus['img'] ?? '',
                                'order_id' => $cus['order_id'],
                                'sku' => $cus['sku'] ?? '',
                                'sku_id' => $cus['sku_id'] ?? 0,
                                'shop_id' => $cus['shop_id'] ?? 0,
                                'fasin' => $cus['fasin'] ?? '',
                                'fasin_code' => $cus['fasin_code'] ?? '',
                            ];
                        }
                    }
                    $img = $this->GetSpuColorImg($item['spu'], $item['color_identifying']);
                    $item['custom_sku_list'] = $customSkuList;
                    $item['name'] = $item['title'];
                    $item['total_price'] = $item['price'];
                    $item['price'] = $item['one_price'];
                    $item['delivery_date'] = $item['report_date'];
                    $item['order_num'] = $item['count'];
                    $item['tag'] = $contractMdl->brand ?? '';
                    $item['cn_name'] = $spu[$item['spu_id']] ?? '';
                    $item['total_num'] = $item['count'];
                    $item['num_info'] = json_decode($item['num_info']) ?? [];
                    $item['size_num'] = $item['num_info'];
                    $item['size_max_num'] = $item['num_info'];
                    $item['size_list'] = $sizeList;
                    $item['size_rule'] = $rule;
                    $item['rule'] = $rule;
                    $item['id'] = $item['order_id'].'-'.$item['spu_id'].'-'.$item['color_identifying'];
                    $item['suppliers_name'] = $contractMdl->supplier_name;
                    $item['suppliers_id'] = $contractMdl->supplier_id;
                    $item['img'] = $img;
                    $spuItems[] = $item;
                }
                $contractMdl->contract_items = $spuItems;
                $contractMdl->size_list = $sizeList;
            }else{
                $spuMdl = db::table('self_spu')
                    ->get()
                    ->keyBy('id');
                $cateMdl = db::table('self_category')
                    ->get()
                    ->keyBy('Id');
                $cloudhouseContract = DB::table('cloudhouse_contract')->where('contract_no', $contractMdl->contract_no)->get();
                $cloudhouseContract = json_decode(json_encode($cloudhouseContract), true);
                foreach ($cloudhouseContract as &$item){
//                    if (array_key_exists($item['spu'].'-'.$item['color_identifying'], $spuList)){
//                        $spuList[$item['spu'].'-'.$item['color_identifying']]['count'] += $item['count'];
//                        $spuList[$item['spu'].'-'.$item['color_identifying']]['price'] += $item['price'];
//                    }else{
//                        $item['num_info'] = json_decode($item['num_info']) ?? [];
//                        $item['size_num'] = $item['num_info'];
//                        $item['size_max_num'] = $item['num_info'];
//                        $item['size_list'] = $size_list;
//                        $spuList[$item['spu'].'-'.$item['color_identifying']] = $item;
//                    }
//                    $spuList[$item['spu'].'-'.$item['color_identifying']]['order_num'] = $item['count'];
//                    $spuList[$item['spu'].'-'.$item['color_identifying']]['tag'] = $contractMdl->brand ?? '';
//                    $spuList[$item['spu'].'-'.$item['color_identifying']]['price'] = $this->floorDecimal($item['price']);
//                    $spuList[$item['spu'].'-'.$item['color_identifying']]['one_price'] = $this->floorDecimal($item['one_price']);
//                    $spuList[$item['spu'].'-'.$item['color_identifying']]['cn_name'] = $spu[$item['spu_id']] ?? '';
//                    $spuList[$item['spu'].'-'.$item['color_identifying']]['total_num'] = $item['count'];
                    $spu = $spuMdl[$item['spu_id']] ?? [];
                    $item['spu'] = !empty($spu->old_spu) ? $spu->old_spu : $spu->spu;
                    $oneCateName = $cateMdl[$spuMdl[$item['spu_id']]->one_cate_id ?? 0]->name ?? '';
                    $threeCateName = $cateMdl[$spuMdl[$item['spu_id']]->three_cate_id ?? 0]->name ?? '';
                    $spuName = $oneCateName.$threeCateName.$item['color_name'];
                    $item['name'] = $spuName;
                    $item['cn_name'] = $spuName;
                    $item['title'] = $spuName;
                    $item['num_info'] = json_decode($item['num_info']) ?? [];
                    $item['size_num'] = $item['num_info'];
                    $item['size_max_num'] = $item['num_info'];
                    $item['size_list'] = $sizeList;
                    $item['rule'] = $rule;
                    $img = $this->GetSpuColorImg($item['spu'], $item['color_identifying']);
                    $item['img'] = $img;
                    $spuList[] = $item;
                }
                $contractMdl->spu_items = array_values($spuList);
                $contractMdl->custom_sku_items = $customSkuItems;
                $contractMdl->size_list = $sizeList;
            }

            $contractMdl->suppliers_link = '';
            $supplier = db::table('suppliers_auxiliary')->where('supplier_id',$contractMdl->supplier_id)->first();
            if($supplier){
                $contractMdl->suppliers_link = $supplier->url_dp;
            }

            $data = $contractMdl;

            return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'; '.$e->getLine()];
        }
    }

    /**
     * @Desc:获取下单详情
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/5/23 10:39
     */
    public function getAmazonPlaceOrderTaskDetail($params)
    {
        try {
            $placeOrderMdl = DB::table('amazon_place_order_task as a')
                ->leftJoin('amazon_place_order_detail as b', 'b.order_id', '=', 'a.id')
                ->whereIn('a.status', [2, 5])
                ->where('b.is_contracted', 0);


            if (isset($params['order_id']) && !empty($params['order_id'])){
                $orderId = explode(',', trim($params['order_id']));
                $placeOrderMdl->whereIn('a.id', $orderId);
            }
            if (isset($params['status']) && !empty($params['status'])){
                $placeOrderMdl->whereIn('a.status', $params['status']);
            }
            if (isset($params['color_id'])){
                $customSkuMdl = db::table('self_custom_sku')
                    ->where('color_id', $params['color_id'])
                    ->get();
                if ($customSkuMdl->isNotEmpty()){
                    $customSkuIds = array_column($customSkuMdl->toArray(), 'id');
                }else{
                    $customSkuIds = [];
                }
                $placeOrderMdl->whereIn('b.custom_sku_id', $customSkuIds);
            }
            if (isset($params['custom_sku']) && !empty($params['custom_sku'])){
                $customSkuMdl = $this->customSkuModel::query()
                    ->where('custom_sku', 'like', '%'.$params['custom_sku'].'%')
                    ->orWhere('old_custom_sku', 'like', '%'.$params['custom_sku'].'%')
                    ->get();
                if ($customSkuMdl->isNotEmpty()){
                    $customSkuIds = array_column($customSkuMdl->toArray(), 'id');
                }else{
                    $customSkuIds = [];
                }
                $placeOrderMdl->whereIn('b.custom_sku_id', $customSkuIds);
            }
            if (isset($params['spu']) && !empty($params['spu'])){
                $spuMdl = $this->spuModel::query()
                    ->where('spu', 'like', '%'.$params['spu'].'%')
                    ->orWhere('old_spu', 'like', '%'.$params['spu'].'%')
                    ->get();
                if ($spuMdl->isNotEmpty()){
                    $supIds = array_column($spuMdl->toArray(), 'id');
                }else{
                    $supIds = [];
                }
                $placeOrderMdl->whereIn('b.spu_id', $supIds);
            }
            $count = $placeOrderMdl->count();

            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page - 1);

            $list = $placeOrderMdl
                ->get(['b.*']);

            $supplierIds = $list->pluck('suppliers_id')->unique();
            $suppliers   = DB::table('suppliers')->whereIn('id', $supplierIds)->select(['id', 'name', 'supplier_no'])->get()->pluck('name', 'id');

            $spuList = [];
            $customSkuList = [];
            $spuArr = [];
            $sizeArr = []; // 保存尺码
            $sizeList = []; // 动态尺码表头 id => name
            $errorMsg = '';
            // 获取成本价
            $spuPrice = db::table('self_spu as a')
                ->leftJoin('self_spu_info as b', 'a.base_spu_id', '=', 'b.base_spu_id')
                ->select(['a.id', 'a.spu', 'a.base_spu_id', 'a.old_spu', 'b.unit_price'])
                ->get()
                ->keyBy('id');
            foreach ($list as $v){
                if (!isset($sizeArr[$v->size])){
                    $sizeArr[] = $v->size;
                    $sizeList[$v->size] = $v->size;
                }
            }
            $customSkuMdl = db::table('self_custom_sku')
                ->get()
                ->keyBy('id');
            $colorSizeMdl = db::table('self_color_size')
                ->get();
            $colorSizeList = [];
            foreach ($colorSizeMdl as $color){
                $colorSizeList[$color->id] = $color;
            }
            $imgList = [];
            $imgMdl = db::table('self_spu_color')
                ->get();
            foreach ($imgMdl as $img){
                $key = $img->base_spu_id.'-'.$img->color_id;
                $imgList[$key] = $img->img ?? '';
            }
            foreach ($list as $item){
                $customSkuInfo = $customSkuMdl[$item->custom_sku_id] ?? [];
                if (empty($customSkuInfo)){
                    $errorMsg .= '库存sku:'.$item->custom_sku.'('.$item->custom_sku_id.')不存在！';
                    continue;
                }
                $item->color_id = $customSkuInfo->color_id ?? 0;
                $spu = $item->spu ?? '';
                if (!isset($colorSizeList[$item->color_id]) || empty($colorSizeList[$item->color_id]->identifying)){
                    $errorMsg .= '库存sku:'.$item->custom_sku.'('.$item->custom_sku_id.')颜色/颜色标识不存在！';
                    continue;
                }
                $item->color_identifying = $colorSizeList[$item->color_id]->identifying;
//                $item->price = $spuPrice[$item->spu_id]->unit_price ?? 0.00;
                $item->price = 0.00;
                $item->name = $customSkuInfo->name ?? $item->name_en;
                $item->base_spu_id = $spuPrice[$item->spu_id]->base_spu_id ?? 0;
                $key = $item->base_spu_id.'-'.$item->color_id;
                $item->img = $imgList[$key] ?? '';
                $item->order_num = array_sum(json_decode($item->order_num, true) ?? []);
                $item->spu = $spuPrice[$item->spu_id]->old_spu ?? $spu;
                $customSku = $item->custom_sku ?? '';
                if (!isset($item->spu_id) || empty($item->spu_id)){
                    $errorMsg .= 'spu:'.$spu.' 未给定标识！请联系开发人员修正！';
                    continue;
                }
                if (!isset($item->custom_sku_id) || empty($item->custom_sku_id)){
                    $errorMsg .= '库存sku:'.$customSku.' 未给定标识！请联系开发人员修正！';
                    continue;
                }
                if (!in_array($item->spu, $spuArr)){
                    $spuArr[] = $item->spu;
                }
                $notContractedNum = bcsub($item->order_num, $item->is_contracted_num);
                $item->not_contracted_num = $notContractedNum;
                $key = $item->order_id.'-'.$item->spu_id.'-'.$item->color_identifying;
                if (isset($spuList[$key])){
                    if (isset($spuList[$key]['size_num'][$item->size])){
//                        $spuList[$key][$item->size] += $item->not_contracted_num;
//                        $spuList[$key][$item->size.'_max_num'] += $item->not_contracted_num;
                        $spuList[$key]['size_num'][$item->size] += $item->not_contracted_num;
                        $spuList[$key]['size_max_num'][$item->size] += $item->not_contracted_num;
                        $spuList[$key]['order_num'] += $item->order_num;
                        $spuList[$key]['custom_sku_list'][] = $item;
                    }else{
                        $errorMsg .= 'spu：'.$item->spu.'尺码：'.$item->size.'非预设值！';
                    }
                }else{
                    $spuList[$key] = [
                        'id' => $item->order_id.'-'.$item->spu_id.'-'.$item->color_identifying,
                        'order_id' => $item->order_id,
                        'spu_id' => $item->spu_id,
                        'spu' => $item->spu,
                        'color_name' => $item->color_name,
                        'color_identifying' => $item->color_identifying,
                        'color_name_en' => $item->color_name_en,
                        'order_num' => $item->order_num,
                        'name' => $item->name_en ?? $item->name,
                        'price' => $item->price,
                        'img' => $item->img ?? '',
                        'custom_sku_list' => [$item],
                        'suppliers_id'      => $item->suppliers_id,
                        'suppliers_name'    => isset($suppliers[$item->suppliers_id]) ? $suppliers[$item->suppliers_id] : '',
                    ];
                    $sizeNum = [];
                    $sizeMaxNum = [];
                    foreach ($sizeArr as $size){
//                        if (!isset($spuList[$key][$size])){
//                            $spuList[$key][$size] = 0;
//                            $spuList[$key][$size.'_max_num'] = 0;
//                        }
                        $sizeNum[$size] = 0;
                        $sizeMaxNum[$size] = 0;
                    }
                    if (isset($sizeNum[$item->size])){
//                        $spuList[$key][$item->size] += $item->not_contracted_num;
//                        $spuList[$key][$item->size.'_max_num'] += $item->not_contracted_num;
                        $sizeNum[$item->size] += $item->not_contracted_num;
                        $sizeMaxNum[$item->size] += $item->not_contracted_num;
                    }else{
                        $errorMsg .= 'spu：'.$item->spu.'尺码：'.$item->size.'非预设值！';
                    }
                    $spuList[$key]['size_num'] = $sizeNum;
                    $spuList[$key]['size_max_num'] = $sizeMaxNum;
                }
                $customSkuList[] = $item;
            }
            if ($errorMsg){
                throw new \Exception($errorMsg);
            }
            $spuList = array_values($spuList);

            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['custom_sku_list' => $customSkuList, 'size_list' => $sizeList, 'count' => count($spuList), 'list' => $spuList]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    /**
     * @Desc:采购下单计划详情选择器
     */
    public function getPurchaseAmazonPlaceOrderTaskDetail($params)
    {
        try {
            $placeOrderMdl = DB::table('amazon_place_order_task as a')
                ->leftJoin('amazon_place_order_detail as b', 'b.order_id', '=', 'a.id')
                ->whereIn('a.status', [2, 5])
                ->where('b.is_contracted', 0);

            if (isset($params['order_id']) && !empty($params['order_id'])) {
                $orderId = explode(',', trim($params['order_id']));
                $placeOrderMdl->whereIn('a.id', $orderId);
            }

            if (isset($params['spu']) && !empty($params['spu'])) {
                $customSkuMdl = $this->spuModel::query()
                    ->where('spu', 'like', '%' . $params['spu'] . '%')
                    ->orWhere('old_spu', 'like', '%' . $params['spu'] . '%')
                    ->get()->keyBy();
                if ($customSkuMdl->isNotEmpty()) {
                    $customSkuIds = array_column($customSkuMdl->toArray(), 'id');
                } else {
                    $customSkuIds = [];
                }
                $placeOrderMdl->whereIn('b.spu_id', $customSkuIds);
            }
            $list    = $placeOrderMdl->get(['b.*']);

            $supplierIds = $list->pluck('suppliers_id')->unique();
            $suppliers   = DB::table('suppliers')->whereIn('id', $supplierIds)->select(['id', 'name', 'supplier_no'])->get()->pluck('name', 'id');

            $spuList = [];
            $customSkuList = [];
            $spuArr = [];
            $sizeArr = []; // 保存尺码
            $sizeList = []; // 动态尺码表头 id => name
            $errorMsg = '';
            // 获取成本价
            $spuPrice = db::table('self_spu as a')
                ->leftJoin('self_spu_info as b', 'a.base_spu_id', '=', 'b.base_spu_id')
                ->select(['a.id', 'a.spu', 'a.base_spu_id', 'a.old_spu', 'b.unit_price'])
                ->get()
                ->keyBy('id');
            foreach ($list as $v){
                if (!isset($sizeArr[$v->size])){
                    $sizeArr[] = $v->size;
                    $sizeList[$v->size] = $v->size;
                }
            }
            $customSkuMdl = db::table('self_custom_sku')
                ->get()
                ->keyBy('id');
            $colorSizeMdl = db::table('self_color_size')
                ->get();
            $colorSizeList = [];
            foreach ($colorSizeMdl as $color){
                $colorSizeList[$color->id] = $color;
            }
            $imgList = [];
            $imgMdl = db::table('self_spu_color')
                ->get();
            foreach ($imgMdl as $img){
                $key = $img->base_spu_id.'-'.$img->color_id;
                $imgList[$key] = $img->img ?? '';
            }
            foreach ($list as $item){
                $customSkuInfo = $customSkuMdl[$item->custom_sku_id] ?? [];
                if (empty($customSkuInfo)){
                    $errorMsg .= '库存sku:'.$item->custom_sku.'('.$item->custom_sku_id.')不存在！';
                    continue;
                }
                $item->color_id = $customSkuInfo->color_id ?? 0;
                $spu = $item->spu ?? '';
                if (!isset($colorSizeList[$item->color_id]) || empty($colorSizeList[$item->color_id]->identifying)){
                    $errorMsg .= '库存sku:'.$item->custom_sku.'('.$item->custom_sku_id.')颜色/颜色标识不存在！';
                    continue;
                }
                $item->color_identifying = $colorSizeList[$item->color_id]->identifying;
//                $item->price = $spuPrice[$item->spu_id]->unit_price ?? 0.00;
//                $item->price = 0.00;
                $item->price = $item->suppliers_price;
                $item->name = $customSkuInfo->name ?? $item->name_en;
                $item->base_spu_id = $spuPrice[$item->spu_id]->base_spu_id ?? 0;
                $key = $item->base_spu_id.'-'.$item->color_id;
                $item->img = $imgList[$key] ?? '';
                $item->order_num = array_sum(json_decode($item->order_num, true) ?? []);
                $spu = $item->spu ?? '';
                $item->spu = $spuPrice[$item->spu_id]->old_spu ?? $spu;
                $customSku = $item->custom_sku ?? '';
                if (!isset($item->spu_id) || empty($item->spu_id)){
                    $errorMsg .= 'spu:'.$spu.' 未给定标识！请联系开发人员修正！';
                    continue;
                }
                if (!isset($item->custom_sku_id) || empty($item->custom_sku_id)){
                    $errorMsg .= '库存sku:'.$customSku.' 未给定标识！请联系开发人员修正！';
                    continue;
                }

                if (!in_array($item->spu, $spuArr)){
                    $spuArr[] = $item->spu;
                }
                $notContractedNum = bcsub($item->order_num, $item->is_contracted_num);
                $item->not_contracted_num = $notContractedNum;
                $key = $item->order_id.'-'.$item->spu_id.'-'.$item->color_identifying;
                if (isset($spuList[$key])){
                    if (isset($spuList[$key]['size_num'][$item->size])){
//                        $spuList[$key][$item->size] += $item->not_contracted_num;
//                        $spuList[$key][$item->size.'_max_num'] += $item->not_contracted_num;
                        $spuList[$key]['size_num'][$item->size] += $item->not_contracted_num;
                        $spuList[$key]['size_max_num'][$item->size] += $item->not_contracted_num;
                        $spuList[$key]['order_num'] += $item->order_num;
                        $spuList[$key]['custom_sku_list'][] = $item;
                    }else{
                        $errorMsg .= 'spu：'.$item->spu.'尺码：'.$item->size.'非预设值！';
                    }
                }else{
                    $spuList[$key] = [
                        'id' => $item->order_id.'-'.$item->spu_id.'-'.$item->color_identifying,
                        'order_id' => $item->order_id,
                        'spu_id' => $item->spu_id,
                        'spu' => $item->spu,
                        'color_name' => $item->color_name,
                        'color_identifying' => $item->color_identifying,
                        'color_name_en' => $item->color_name_en,
                        'order_num' => $item->order_num,
                        'name' => $item->name_en ?? $item->name,
                        'price' => $item->price,
                        'img' => $item->img ?? '',
                        'custom_sku_list' => [$item],
                        'suppliers_id'      => $item->suppliers_id,
                        'suppliers_name'    => isset($suppliers[$item->suppliers_id]) ? $suppliers[$item->suppliers_id] : '',
                    ];
                    $sizeNum = [];
                    $sizeMaxNum = [];
                    foreach ($sizeArr as $size){
//                        if (!isset($spuList[$key][$size])){
//                            $spuList[$key][$size] = 0;
//                            $spuList[$key][$size.'_max_num'] = 0;
//                        }
                        $sizeNum[$size] = 0;
                        $sizeMaxNum[$size] = 0;
                    }
                    if (isset($sizeNum[$item->size])){
//                        $spuList[$key][$item->size] += $item->not_contracted_num;
//                        $spuList[$key][$item->size.'_max_num'] += $item->not_contracted_num;
                        $sizeNum[$item->size] = $item->not_contracted_num;
                        $sizeMaxNum[$item->size] = $item->not_contracted_num;
                    }else{
                        $errorMsg .= 'spu：'.$item->spu.'尺码：'.$item->size.'非预设值！';
                    }
                    $spuList[$key]['size_num'] = $sizeNum;
                    $spuList[$key]['size_max_num'] = $sizeMaxNum;
                }
                $customSkuList[] = $item;
            }
            if ($errorMsg){
                throw new \Exception($errorMsg);
            }
            $spuList = array_values($spuList);

            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['custom_sku_list' => $customSkuList, 'size_list' => $sizeList, 'count' => count($spuList), 'list' => $spuList]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function formatContractItems($params)
    {
        try {
            if (!isset($params['contract_items']) || empty($params['contract_items'])){
                throw new \Exception("未选择商品明细信息！");
            }
            $spuList = [];
            $customSkuList = [];
            $spuArr = [];
            $errorMsg = '';
            $customSkuItems = []; // 保存要更新的amazon_place_order_detail is_contracted的数据
            $contractTotalNum = 0; // 合同总数量
            $contractTotalAmount = 0.00; // 合同总价格
            $contractSkuNum = [];
            if (isset($params['id'])){
                $contractMdl = db::table('cloudhouse_contract_total')->where('id', $params['id'])->first();
                if (empty($params)){
                    throw new \Exception('未查询到合同数据！');
                }
                $contractSkuMdl = db::table('cloudhouse_custom_sku')
                    ->where('contract_no', $contractMdl->contract_no)
                    ->get();
                foreach ($contractSkuMdl as $cSku) {
                    $key = $cSku->order_id.'-'.$cSku->custom_sku_id;
                    if(isset($contractSkuNum[$key])){
                        $contractSkuNum[$key] += $cSku->num;
                        $customSkuItems[$key]['num'] += $cSku->num;
                    }else{
                        $contractSkuNum[$key] = $cSku->num;
                        $customSkuItems[$key] = [
                            'order_id' => $cSku->order_id,
                            'custom_sku_id' => $cSku->custom_sku_id,
                            'num' => $cSku->num
                        ];
                    }

                }
            }
            $orderMdl = DB::table('amazon_place_order_detail')
                ->whereIn('order_id', explode(',', $params['bind_place_ids']))
                ->get();
            $orderNotContractedNumList = [];
            foreach ($orderMdl as $order){
                $key = $order->order_id.'-'.$order->custom_sku_id;
                $orderNum = array_sum(json_decode($order->order_num));
                $isContractedNum = $order->is_contracted_num;
                if (isset($params['id'])){
                    if (isset($contractSkuNum[$key])){
                        $isContractedNum = $order->is_contracted_num - $contractSkuNum[$key];
                    }
                }

                $orderNotContractedNumList[$key] = $orderNum - $isContractedNum;
            }
            $customSkuArr = [];
            $customSkuMdl = db::table('self_custom_sku')
                ->get();
            foreach ($customSkuMdl as $_sku){
                $key = $_sku->spu_id.'-'.$_sku->color.'-'.$_sku->size;
                $customSkuArr[$key] = $_sku->id;
            }
            foreach ($params['contract_items'] as $item){
                $spu = $item['spu'] ?? '';
                $customSku = $item['custom_sku'] ?? '';
                if (!isset($item['price']) || $item['price'] < 0){
                    $errorMsg .= 'spu:'.$spu.' 价格不合法！';
                    continue;
                }
                if (!in_array($item['spu'], $spuArr)){
                    $spuArr[] = $item['spu'];
                }
                $sizeNum = [];
                $spuCount = 0;
                $spuAccount = 0;
                $item['size_rule'] = array_unique($item['size_rule']);
                foreach ($item['size_rule'] as $rule){
                    $num = $item['size_num'][$rule] ?? 0;
                    $customSkuId = $customSkuArr[$item['spu_id'].'-'.$item['color_identifying'].'-'.$rule] ?? 0;
                    if (empty($customSkuId)){
//                        $errorMsg .= 'SPU：'.$item['spu'].'-'.$item['color_name'].'-'.$rule.'该库存sku数据不存在！';
                        continue;
                    }
                    $_key = $item['order_id'].'-'.$customSkuId;
                    $notContractedNum = $orderNotContractedNumList[$_key] ?? 0;
                    if ($notContractedNum < $item['size_num'][$rule]){
                        $errorMsg .= 'SPU：'.$item['spu'].'-'.$item['color_name'].'-'.$rule.'，开合同数量为：'.$num.'，该下单id：'.$item['order_id'].'可开合同数量为：'.$notContractedNum.'，差额为：'.bcsub($num, $notContractedNum)."\n";
                        continue;
                    }
                    $sizeNum[$rule] = $num;
                    $contractTotalNum += $num;
                    $contractTotalAmount += $item['price'] * $num;
                    $spuCount += $num;
                    $spuAccount += $item['price'] * $num;
                }
                foreach ($item['custom_sku_list'] as $cus){
                    $key = $cus['order_id'].'-'.$cus['custom_sku_id'];
                    $size_max_num = $orderNotContractedNumList[$key] ?? 0;
                    $num = $sizeNum[$cus['size']] ?? 0;
                    if ($num > $size_max_num){
                        $errorMsg .= 'SPU：'.$cus['spu'].'-'.$cus['color_identifying'].'-'.$cus['color_name'].'，开合同数量为：'.$num.'，该下单id：'.$cus['order_id'].'可开合同数量为：'.$size_max_num.'，差额为：'.bcsub($num, $size_max_num)."\n";
                    }
                    if (isset($customSkuItems[$key])){
                        $customSkuItems[$key]['num'] -= $num;
                    }else{
                        $customSkuItems[$key] = [
                            'order_id' => $cus['order_id'],
                            'custom_sku_id' => $cus['custom_sku_id'],
                            'num' => bcsub(0,$num)
                        ];
                    }
                    $customSkuList[] = [
                        'spu_id' => $cus['spu_id'],
                        'custom_sku_id' => $cus['custom_sku_id'],
                        'spu' => $cus['spu'],
                        'custom_sku' => $cus['custom_sku'],
                        'color_name' => $cus['color_name'],
                        'color_name_en' => $cus['color_name_en'],
                        'color_identifying' => $cus['color_identifying'],
                        'size' => $cus['size'],
                        'order_num' => $num,
                        'name' => $cus['name'] ?? '',
                        'delivery_date' => $item['delivery_date'],
                        'price' => $item['price'],
                        'img' => $cus['img'] ?? '',
                        'order_id' => $item['order_id'],
                        'sku' => $cus['sku'] ?? '',
                        'sku_id' => $cus['sku_id'] ?? 0,
                        'shop_id' => $cus['shop_id'] ?? 0,
                        'fasin' => $cus['fasin'] ?? '',
                        'fasin_code' => $cus['fasin_code'] ?? '',
                    ];
                }

                $spuList[] = [
                    'order_id' => $item['order_id'],
                    'spu_id' => $item['spu_id'],
                    'spu' => $item['spu'],
                    'color_name' => $item['color_name'],
                    'color_identifying' => $item['color_identifying'],
                    'color_name_en' => $item['color_name_en'] ?? '',
                    'count' => $spuCount,
                    'title' => $item['name'] ?? '',
                    'report_date' => $item['delivery_date'],
                    'price' => $spuAccount,
                    'one_price' => $item['price'],
                    'img' => $item['img'] ?? '',
                    'num_info' => json_encode($sizeNum),
                    'rule' => implode(',',$item['size_rule']),
                    'memo' => $item['memo'] ?? ''
                ];
            }

            if (!empty($errorMsg)){
                throw new \Exception('商品信息有误！详情：'.$errorMsg);
            }
            $contractTotalNum = $this->floorDecimal($contractTotalNum);
            $contractTotalAmount = $this->floorDecimal($contractTotalAmount);

            return ['spu_list' => $spuList, 'custom_sku_list' => $customSkuList, 'spu_count' => count($spuArr), 'custom_sku_items' => $customSkuItems, 'contract_total_num' => $contractTotalNum, 'contract_total_amount' => $contractTotalAmount];
        }catch (\Exception $e){
            throw new \Exception('处理失败！原因：'.$e->getMessage().'; 错误位置：'.$e->getLine());
        }
    }

    /**
     * @Desc:提交合同
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/5/6 17:27
     */
    public function submitAmazonPlaceOrderContract($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给定合同标识！');
            }
            $contractMdl = DB::table('cloudhouse_contract_total')
                ->where('id', $params['id'])
                ->first();
            if (empty($contractMdl)){
                throw new \Exception('未查询到该合同的信息！');
            }
            if (empty($contractMdl->contract_class)){
                throw new \Exception('该合同为艾诺科同步的合同，请勿重复提交审核！');
            }
            if (!in_array($contractMdl->contract_status, [-1, 0, -2])){
                throw new \Exception('非撤销/草拟/被拒绝状态不可提交合同！');
            }
            $makerName = $this->GetUsers($contractMdl->maker_id)['account'] ?? '';
            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['maker_id' => $contractMdl->maker_id, 'maker_name' => $makerName,'contract_id'=>$contractMdl->id, 'contract_no' => $contractMdl->contract_no, 'contract_link' => '/sale_agreement_details?contract_no='.$contractMdl->contract_no, 'request_type' => 23, 'total_count' => $contractMdl->total_count, 'total_price' => $this->floorDecimal($contractMdl->total_price), 'report_date' => $contractMdl->report_date]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '提交失败！错误原因：'.$e->getMessage()];
        }
    }

    public function revokeAmazonPlaceOrderContract($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给定合同标识！');
            }
            $contractMdl = DB::table('cloudhouse_contract_total')
                ->where('id', $params['id'])
                ->first();
            if (empty($contractMdl)){
                throw new \Exception('未查询到该合同的信息！');
            }
            if (!in_array($contractMdl->contract_status, [1, 2])){
                throw new \Exception('非待审核/审核通过状态不可撤销合同！');
            }
            if ($contractMdl->contract_status == 1){
                $contract = DB::table('cloudhouse_contract_total')->where('id', $params['id'])->update(['contract_status' => -1]);
                $placIds = explode(',', $contractMdl->bind_place_ids);
                foreach ($placIds as $id){
                    $placeOrder = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 3]);
                }
                $task = DB::table('tasks')->where('ext', 'like', '%contract_no='.$contractMdl->contract_no.'%')->update(['is_deleted' => 1]);
            }elseif ($contractMdl->contract_status == 2){
                $billMdl = db::table('financial_bill')
                    ->where('contract_no', 'like', '%'.$contractMdl->contract_no.'%')
                    ->where('status', '<>', '-3')
                    ->first();
                if (!empty($billMdl)){
                    throw new \Exception('合同号：'.$contractMdl->contract_no.'存在非废弃票据，不可反审核！');
                }else{
                    $makerName = $this->GetUsers($contractMdl->maker_id)['account'] ?? '';
                    return ['code' => 200, 'msg' => '获取成功！', 'data' => ['maker_id' => $contractMdl->maker_id, 'maker_name' => $makerName,'contract_id'=>$contractMdl->id, 'contract_no' => $contractMdl->contract_no, 'contract_link' => '/sale_agreement_details?contract_no='.$contractMdl->contract_no, 'request_type' => 78, 'total_count' => $contractMdl->total_count, 'total_price' => $this->floorDecimal($contractMdl->total_price), 'report_date' => $contractMdl->report_date]];
                }
            }

            return ['code' => 200, 'msg' => '撤销成功！'];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '撤销失败！错误原因：'.$e->getMessage()];
        }
    }

    public function exportPlaceOrderContractDetail_old($params)
    {
//        var_dump(phpinfo());exit();
        try{
            if (isset($params['id']) && !empty($params['id'])){
                $contractMdl = DB::table('cloudhouse_contract_total')->where('id', $params['id'])
                    ->first();
                if (empty($contractMdl)){
                    throw new \Exception('未查询到该合同信息！');
                }
//                if ($contractMdl->contract_status != 2){
//                    throw new \Exception('该合同还未审批通过，不予打印！');
//                }
                $contractSpuMdl = DB::table('cloudhouse_contract')->where('contract_no', $contractMdl->contract_no)->get();
                $contractSpuMdl = json_decode(json_encode($contractSpuMdl), true);
                $spuList = [];
                $sizeArr = ['XXS','XS','2XL','3XL','4XL','5XL','6XL','7XL','8XL','S','M','XL','L'];
                foreach ($contractSpuMdl as &$item){
                    if (array_key_exists($item['spu'].'-'.$item['color_identifying'], $spuList)){
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['XXS'] += $item['XXS'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['XS'] += $item['XS'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['S'] += $item['S'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['M'] += $item['M'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['L'] += $item['L'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['XL'] += $item['XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['2XL'] += $item['2XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['3XL'] += $item['3XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['4XL'] += $item['4XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['5XL'] += $item['5XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['6XL'] += $item['6XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['7XL'] += $item['7XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['8XL'] += $item['8XL'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['count'] += $item['count'];
                        $spuList[$item['spu'].'-'.$item['color_identifying']]['price'] += $item['price'];
                    }else{
                        $spuList[$item['spu'].'-'.$item['color_identifying']] = $item;
                    }
                    $spuList[$item['spu'].'-'.$item['color_identifying']]['order_num'] = $item['count'];
                }
                $contractSpuMdl = json_decode(json_encode(array_values($spuList)), false);
            }else{
                throw new \Exception('未给定合同标识！');
            }
            $obj = new \PHPExcel();

            $fileName = "下单合同".$contractMdl->contract_no. '-' . date('Y-m-d', microtime(true));
            $fileType = 'xlsx';

            // 处理样式
            $obj->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); // 水平居中
            $obj->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//设置默认垂直居中


            $sheet = $obj->getActiveSheet(); // 处理工作表单元格
//            $sheet->getDefaultRowDimension()->setRowHeight(13); // 设置所有单元格行高自适应（无效果）
//            $sheet->getDefaultColumnDimension()->setWidth(4);
            $sheet->getDefaultRowDimension()->setRowHeight(40);
            $column = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA'];
            foreach ($column as $col){
                $sheet->getColumnDimension($col)->setWidth(3.4);
                $sheet->getStyle($col)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行
            }
//            for ($i = 1; $i <= 200; $i++){
//                $sheet->getRowDimension($i)->setRowHeight(15);
//            }
            $sheet->getStyle('A1:AA99')->getFont()->setName('宋体'); // 设置字体
            $sheet->mergeCells('A1:AA1'); // 合并单元格
            $sheet->setCellValue('A1', $contractMdl->company_name.'购销合同'); // 单元格填充数据
            $sheet->getStyle('A1')->getFont()->setSize(14); // 设置字体大小
            $sheet->getStyle('A1')->getFont()->setBold(true); // 是否加粗

            $sheet->mergeCells('A2:AA2'); // 合并单元格

            $sheet->mergeCells('A3:B3'); // 合并单元格
            $sheet->mergeCells('C3:H3'); // 合并单元格
            $sheet->mergeCells('S3:T3'); // 合并单元格
            $sheet->mergeCells('U3:AA3'); // 合并单元格
            $sheet->setCellValue('A3', '甲方单位：'); // 单元格填充数据
            $sheet->setCellValue('C3', $contractMdl->company_name); // 单元格填充数据
            $sheet->setCellValue('S3', '合同编号：'); // 单元格填充数据
            $sheet->setCellValue('U3', $contractMdl->contract_no); // 单元格填充数据

            $sheet->mergeCells('A4:B4'); // 合并单元格
            $sheet->mergeCells('C4:H4'); // 合并单元格
            $sheet->mergeCells('S4:T4'); // 合并单元格
            $sheet->mergeCells('U4:AA4'); // 合并单元格
            $sheet->setCellValue('A4', '乙方单位：'); // 单元格填充数据
            $sheet->setCellValue('C4', $contractMdl->supplier_short_name); // 单元格填充数据
            $sheet->setCellValue('S4', '签约时间：'); // 单元格填充数据
            $sheet->setCellValue('U4', $contractMdl->sign_date); // 单元格填充数据

            $sheet->mergeCells('A5:B5'); // 合并单元格
            $sheet->mergeCells('C5:H5'); // 合并单元格
            $sheet->setCellValue('A5', '供应商编码：'); // 单元格填充数据
            $sheet->setCellValue('C5', $contractMdl->supplier_no ?? ''); // 单元格填充数据

            $sheet->mergeCells('S5:T5'); // 合并单元格
            $sheet->mergeCells('U5:AA5'); // 合并单元格
            $sheet->setCellValue('S5', '签约地点：'); // 单元格填充数据
            $sheet->setCellValue('U5', $contractMdl->signing_location); // 单元格填充数据

            $sheet->mergeCells('S6:T6'); // 合并单元格
            $sheet->mergeCells('U6:AA6'); // 合并单元格
            $sheet->setCellValue('S6', '交期时间：'); // 单元格填充数据
            $sheet->setCellValue('U6', $contractMdl->report_date); // 单元格填充数据

            $sheet->getStyle('A3:AA6')->getFont()->setSize(7); // 设置字体大小
            $sheet->getStyle('A3:AA6')->getFont()->setBold(true); // 是否加粗
            $sheet->getStyle('C3:H4')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('U3:AA6')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $sheet->mergeCells('A7:AA7'); // 合并单元格
            $sheet->setCellValue('A7', '为促进甲方、乙方双方合作顺利开展，保障双方权益，根据《中华人民共和国民法典》及相关法律法规的规定，经双方友好协商特订立本合同，供共同遵守。'); // 单元格填充数据

            $sheet->mergeCells('A8:AA8'); // 合并单元格

            $sheet->mergeCells('A9:AA9'); // 合并单元格
            $sheet->setCellValue('A9', '一、 1、甲方商品的款号/品名，数量，单价，金额（人民币）'); // 单元格填充数据

            $sheet->getStyle('A7:AA9')->getFont()->setSize(8); // 设置字体大小
            $sheet->getStyle('A7:AA9')->getFont()->setBold(true); // 是否加粗
            $sheet->getStyle('A7:AA9')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row = 10;

            $sheet->mergeCells('A'.$row.':D'.$row); // 合并单元格
            $sheet->mergeCells('E'.$row.':H'.$row); // 合并单元格
            $sheet->mergeCells('T'.$row.':U'.$row); // 合并单元格
            $sheet->mergeCells('V'.$row.':W'.$row); // 合并单元格
            $sheet->mergeCells('X'.$row.':Y'.$row); // 合并单元格
            $sheet->mergeCells('Z'.$row.':AA'.$row); // 合并单元格

            $size = ['S','M','L','XL','2XL','3XL','4XL','5XL','6XL'];
            $col = ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S'];
            foreach ($col as $k => $c){
                $sheet->setCellValue($c.$row, $size[$k]); // 单元格填充数据
                $sheet->getStyle('K'.$row.':S'.$row)->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            }

            $sheet->getStyle('A'.$row.':D'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('E'.$row.':H'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('T'.$row.':U'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('V'.$row.':W'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('X'.$row.':Y'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('Z'.$row.':AA'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('I'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('J'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

            $sheet->setCellValue('A'.$row, '款号'); // 单元格填充数据
            $sheet->setCellValue('E'.$row, '款式'); // 单元格填充数据
            $sheet->setCellValue('I'.$row, '品名'); // 单元格填充数据
            $sheet->setCellValue('J'.$row, '尺码颜色'); // 单元格填充数据
            $sheet->setCellValue('T'.$row, '合计（件）'); // 单元格填充数据
            $sheet->setCellValue('V'.$row, '单价（含税）'); // 单元格填充数据
            $sheet->setCellValue('X'.$row, '金额（含税）'); // 单元格填充数据
            $sheet->setCellValue('Z'.$row, '备注'); // 单元格填充数据

            $sheet->getStyle('K'.$row.':'.'S'.$row)->getFont()->setName(); // 设置字体
            $sheet->getStyle('A'.$row.':AA'.$row)->getFont()->setSize(8); // 设置字体大小
            $sheet->getStyle('A'.$row.':AA'.$row)->getFont()->setBold(true); // 是否加粗

            $colTotal = [];
//            $totalNum = 0;
//            $totalPrice = 0;
            $sizes = [];
            foreach ($contractSpuMdl as $v) {
                $sizeArr = []; // 保存尺码数量 ['S' => 40, 'M' => 60];
                $sizeArrKey = []; // 保存尺码['S', 'M'];
                foreach ($size as $s) {
                    $sizeArr[$s] = $v->$s;
                    $sizeArrKey[] = $s;
                    if ($v->$s){
                        $sizes[] = $s;
                    }
                }

                $sheet->mergeCells('A' . ($row + 1) . ':D' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('E' . ($row + 1) . ':H' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('I' . ($row + 1) . ':I' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('J' . ($row + 1) . ':J' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('K' . ($row + 1) . ':K' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('L' . ($row + 1) . ':L' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('M' . ($row + 1) . ':M' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('N' . ($row + 1) . ':N' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('O' . ($row + 1) . ':O' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('P' . ($row + 1) . ':P' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('Q' . ($row + 1) . ':Q' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('R' . ($row + 1) . ':R' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('S' . ($row + 1) . ':S' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('T' . ($row + 1) . ':U' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('V' . ($row + 1) . ':W' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('X' . ($row + 1) . ':Y' . ($row + 3)); // 合并单元格
                $sheet->mergeCells('Z' . ($row + 1) . ':AA' . ($row + 3)); // 合并单元格

                $sheet->getStyle('A' . ($row + 1) . ':D' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('E' . ($row + 1) . ':H' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('I' . ($row + 1) . ':' . 'I' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('J' . ($row + 1) . ':' . 'J' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('T' . ($row + 1) . ':' . 'U' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('V' . ($row + 1) . ':' . 'W' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('X' . ($row + 1) . ':' . 'Y' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('Z' . ($row + 1) . ':' . 'AA' . ($row + 3))->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

                // 尺码及尺码数量
                foreach ($col as $k => $c) {
//                    $col_name = $sizeArrKey[$key] ?? '';
                    $col_num = $sizeArr[$sizeArrKey[$k]] ?? 0;
                    $sheet->setCellValue($c.($row+1), $col_num); // 单元格填充数据
                    $sheet->getStyle($c . ($row + 1) . ":" . $c . ($row + 3))->getBorders()->getAllBorders()
                        ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                    if (array_key_exists($c, $colTotal)) {
                        $colTotal[$c] += $col_num;
                    } else {
                        $colTotal[$c] = $col_num;
                    }
                }

//                $img = DB::table('self_color_size as a')->leftJoin('self_spu_color as b', 'a.id', '=', 'b.color_id')
//                    ->where('a.identifying', $v->color_identifying)
//                    ->where('b.spu', $v->spu)
//                    ->first();
//                // 导出网络图片地址处理
                $img = $v->img ?? '';
//                if (!empty($img)){
//                    $arr = explode(".", $img);
//                    $ext = end($arr);
//                    if ($ext == 'jpg'){
//                        $img = @imagecreatefromjpeg($img);
//                    }
//                    if ($ext == 'gif'){
//                        $img =  @imagecreatefromgif($img);
//                    }
//                    if ($ext == 'png'){
//                        $img = @imagecreatefrompng($img);
//                    }
//                    //实例化图片操作类
//                    $objDrawing  = new \PHPExcel_Worksheet_MemoryDrawing();
//                    $objDrawing->setImageResource($img);
//                    //渲染方法
//                    $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT);
//                    $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
//                    $objDrawing->setCoordinates('F'.($row+1)); // 设置图片存放在表格的位置
//                    // 设置图片高
//                    $objDrawing->setHeight(50);
//                    // 设置X方向偏移量
//                    $objDrawing->setOffsetX(50);
//                    // 设置Y方向偏移量
//                    $objDrawing->setOffsetY(5);
//                    $objDrawing->getShadow()->setVisible (true );
//                    $objDrawing->getShadow()->setDirection(45);
//                    $objDrawing->setWorksheet($sheet);
                if ($img) {
                    $name = str_replace('http://q.zity.cn/', '/var/www/online/zity/public/admin/excel_img/', $img);
                    // echo $name;
                    if ($name) {
                        $a = $this->httpcopy($img, $name);
                        if ($a['err']) {
                            $imgtype = 'jpg';
                            if (strpos($img, 'png')) {
                                $imgtype = 'png';
                            }
                            $name = '/var/www/online/zity/public/admin/excel_img/' . rand(1, 100) . time() . '.' . $imgtype;
                            $ab = $this->httpcopy($img, $name);
                            if ($ab['err']) {
                                $name = '';
                            }
                        }

                        if (is_file($name)) {
                            $img = $name;
                            $objDrawing = new \PHPExcel_Worksheet_Drawing();
                            // 获取图片地址
                            $objDrawing->setPath($img);
                            // 设置图片存放在表格的位置
                            $objDrawing->setCoordinates('E' . ($row + 1));
//                            // 设置表格宽度
                            $sheet->getColumnDimension('C')->setWidth(0.7);
                            $sheet->getColumnDimension('D')->setWidth(0.7);
                            $sheet->getColumnDimension('E')->setWidth(0.7);
                            $sheet->getColumnDimension('F')->setWidth(0.7);
                            $sheet->getColumnDimension('G')->setWidth(0.7);
//                            // 设置表格高度
                            $sheet->getRowDimension(($row + 1))->setRowHeight(10);
                            // 设置图片宽
                            $objDrawing->setWidth(20);
//                            // 设置图片高
                            $objDrawing->setHeight(25);
                            // 设置X方向偏移量
                            $objDrawing->setOffsetX(10);
                            // 设置Y方向偏移量
                            $objDrawing->setOffsetY(8);
                            $objDrawing->getShadow()->setVisible (true );
                            $objDrawing->getShadow()->setDirection(45);
                            $objDrawing->setWorksheet($sheet);
                        } else {
                            $img = $name;
                        }
                    }
                }

                $sheet->setCellValue('A'.($row+1), $v->spu); // 单元格填充数据
//                $sheet->setCellValue('E'.($row+1), $img->img); // 单元格填充数据
                $sheet->setCellValue('I'.($row+1), $v->title); // 单元格填充数据
                $sheet->setCellValue('J'.($row+1), $v->color_name.'/'.$v->color_identifying); // 单元格填充数据
                $sheet->setCellValue('T'.($row+1), $v->count); // 单元格填充数据
                $sheet->setCellValue('V'.($row+1), $v->one_price); // 单元格填充数据
                $sheet->setCellValue('X'.($row+1), $v->price); // 单元格填充数据
                $sheet->setCellValue('Z'.($row+1), $contractMdl->memo); // 单元格填充数据

//                $totalNum += $v->count;
//                $totalPrice += $v->price;
                $sheet->getStyle('I'.($row+1))->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行
//                $sheet->getStyle('I'.($row+1))->getAlignment()->setShrinkToFit(true);   //自动转换显示字体大小,使内容能够显示

//                $sheet->getRowDimension('A'.($row+1).':AA'.($row+1))->setRowHeight(230);
                $row += 3;
            }

            // 合计金额
            $row += 1;
            $sheet->mergeCells('A'.$row.':J'.$row); // 合并单元格
            $sheet->mergeCells('T'.$row.':U'.$row); // 合并单元格
            $sheet->mergeCells('V'.$row.':W'.$row); // 合并单元格
            $sheet->mergeCells('X'.$row.':Y'.$row); // 合并单元格
            $sheet->mergeCells('Z'.$row.':AA'.$row); // 合并单元格

            $sheet->setCellValue('A'.$row, '合计金额'); // 单元格填充数据
            $sheet->setCellValue('T'.$row, $contractMdl->total_count); // 单元格填充数据
            $sheet->setCellValue('X'.$row, $contractMdl->total_price); // 单元格填充数据

            $sheet->getStyle('A'.$row.':J'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('T'.$row.':U'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('V'.$row.':W'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('X'.$row.':Y'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $sheet->getStyle('Z'.$row.':AA'.$row)->getBorders()->getAllBorders()
                ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

            foreach ($col as $c){
                $sheet->setCellValue($c.$row, $colTotal[$c] ?? 0); // 单元格填充数据
                $sheet->getStyle($c.$row)->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            }

            $sheet->getStyle('A'.$row)->getFont()->setSize(8); // 设置字体大小
            $sheet->getStyle('A'.$row)->getFont()->setBold(true); // 是否加粗
            $sheet->getStyle('T'.$row)->getFont()->setSize(8); // 设置字体大小
            $sheet->getStyle('T'.$row)->getFont()->setBold(true); // 是否加粗
            $sheet->getStyle('X'.$row)->getFont()->setSize(8); // 设置字体大小
            $sheet->getStyle('X'.$row)->getFont()->setBold(true); // 是否加粗

            $row += 1;
            $payment_information = json_decode($contractMdl->payment_information, true) ?? [];
            foreach ($payment_information as $item){
                $sheet->mergeCells('A'.$row.':J'.$row); // 合并单元格
                $sheet->mergeCells('K'.$row.':AA'.$row); // 合并单元格
                $sheet->setCellValue('A'.$row, $item['title']); // 单元格填充数据
                $sheet->setCellValue('K'.$row, $item['money']); // 单元格填充数据

                $sheet->getStyle('K'.$row)->getFont()->setSize(8); // 设置字体大小
                $sheet->getStyle('K'.$row)->getFont()->setBold(true); // 是否加粗

                $sheet->getStyle('A'.$row.':J'.$row)->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                $sheet->getStyle('K'.$row.':AA'.$row)->getBorders()->getAllBorders()
                    ->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

                $row += 1;
            }

            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sizes = implode('、', array_unique($sizes));
            $sheet->setCellValue('A'.$row, "2、需提供产前确认样（拍照样）齐色".$sizes."码各一件。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->getRowDimension('A'.$row)->setRowHeight();//自适应行高（无效）
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->getRowDimension($row)->setRowHeight(50);
            $sheet->setCellValue('A'.$row, "3、出货良品率保持99%，按合同规定的交货期交货，若逾期大于8天以上的，延一天按万分之7.5扣款，≥31天 除了扣款还需承担甲方运费。(如有其他原因延期交货，双方友好协商交货日期，并以书面或者邮件给以通知，须甲方同意为准，不可延期后再进行延期补签申请）。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "二、质量要求技术标准、乙方对质量负责的条件:"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "1、产品质量和材料以需方提供的原样一致及双方最终签章确认产前样为准！如有不一致，甲方有权取消本次合同。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "2、必须符合国家法定商检标准及甲方提出的质量标准,按照AQL2.5质量标准进行验货。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "三、交货地点、方式及运输费用"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "1、须按甲方提供的交货期及指定的地点交货，我方地址分别为：厦门同安仓、泉州仓、厦门软二仓。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "2、乙方按甲方指定地点送货，在保证交货期情况下乙方可自主选择运输方式，运输费用乙方承担。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "四、包装标准：按我司要求包装（详细按理单资料）"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "五、验收标准、方法及提出异议期限："); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "1、甲方派出的QC以确认样和国家法定商检标准为准，对产品的品质、规格、数量、包装等外观质检验。乙方须严格按甲方要求执行。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "2、 按确认样和制作单要求生产。乙方未能按质按量按时交货引起的损失，概由乙方承担。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "2、甲方在收货后有权对因工厂生产技术、材料等方面造成的质量问题提出索赔、严重者可提出退货及索赔，乙方应予以接受。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "六、货款的计算及结算方式："); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->getRowDimension($row)->setRowHeight();
            $sheet->setCellValue('A'.$row, $contractMdl->payment_settlement_method); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "七、违约责任："); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "2、乙方所交货品与本合同规定质量不符导致甲方在转售该批服装时被客人拒绝接收或降价或其它救济方式时，甲方有权对乙方采取相应的措施，乙方不得拒绝。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "3、因乙方不能按期交货，甲方不同意延期所引起的各项运费或制约款等费用由乙方承担。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "八、解决合同纠纷方式："); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "合同履行过程中若发生纠纷，经友好协商未果提起诉讼，由签约地（厦门思明区）法院管辖。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "九、其它约定事项:"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "1、由甲方提供的理单资料（即大货要求）均为本合同附件，其它未尽事宜可经双方商定进行书面修改补充并视为本合同不可分割的部分，同样具有法律效力。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "2、大货材料必须由甲方确认后才可生产，否则由此引起的责任及后果由乙方承担;"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "3、甲方品牌产品、组合方式、设计款式、包装方式等待均不可销售其他电商卖家。如发现乙方向其他电商卖家销售以上规定的产品造成甲方损失应由乙方承担。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "3、甲方品牌产品、组合方式、设计款式、包装方式等待均不可销售其他电商卖家。如发现乙方向其他电商卖家销售以上规定的产品造成甲方损失应由乙方承担。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "4、如果是因为乙方质量等原因，造成甲方派QC前往乙方工厂验货超过3次的，所产生的验货费用由乙方承担。 （根据验货地点费用起：500元-1000元以上）"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "5、乙方须在交货前免费提供符合甲方质量要求的初样，修改样，产前样，大货样，若不符合要求，须重新提供。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "6、乙方必须做产前样给甲方确认后，方可开裁&生产大货，否则后果将由乙方负全部责任。"); // 单元格填充数据
            $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':AA'.$row); // 合并单元格

            $row += 1;
            $sheet->mergeCells('A'.$row.':B'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "甲方单位："); // 单元格填充数据
            $sheet->mergeCells('C'.$row.':H'.$row); // 合并单元格
            $sheet->setCellValue('C'.$row, $contractMdl->company_name); // 单元格填充数据
            $sheet->mergeCells('O'.$row.':P'.$row); // 合并单元格
            $sheet->setCellValue('O'.$row, "乙方单位："); // 单元格填充数据
            $sheet->mergeCells('Q'.$row.':V'.$row); // 合并单元格
            $sheet->setCellValue('Q'.$row, $contractMdl->supplier_short_name); // 单元格填充数据
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':B'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "地址："); // 单元格填充数据
            $sheet->mergeCells('C'.$row.':H'.$row); // 合并单元格
            $sheet->setCellValue('C'.$row, ""); // 单元格填充数据
            $sheet->mergeCells('O'.$row.':P'.$row); // 合并单元格
            $sheet->setCellValue('O'.$row, "地址："); // 单元格填充数据
            $sheet->mergeCells('Q'.$row.':V'.$row); // 合并单元格
            $sheet->setCellValue('Q'.$row, ""); // 单元格填充数据
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':B'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "甲方代表："); // 单元格填充数据
            $sheet->mergeCells('C'.$row.':H'.$row); // 合并单元格
            $makerName = $this->GetUsers($contractMdl->maker_id)['account'] ?? '';
            $sheet->setCellValue('C'.$row, $makerName); // 单元格填充数据
            $sheet->mergeCells('O'.$row.':P'.$row); // 合并单元格
            $sheet->setCellValue('O'.$row, "乙方代表："); // 单元格填充数据
            $sheet->mergeCells('Q'.$row.':V'.$row); // 合并单元格
            $sheet->setCellValue('Q'.$row, ""); // 单元格填充数据
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':B'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "签章："); // 单元格填充数据
            $sheet->mergeCells('C'.$row.':H'.$row); // 合并单元格
            $sheet->setCellValue('C'.$row, ""); // 单元格填充数据
            $sheet->mergeCells('O'.$row.':P'.$row); // 合并单元格
            $sheet->setCellValue('O'.$row, "签章："); // 单元格填充数据
            $sheet->mergeCells('Q'.$row.':V'.$row); // 合并单元格
            $sheet->setCellValue('Q'.$row, ""); // 单元格填充数据
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            $row += 1;
            $sheet->mergeCells('A'.$row.':B'.$row); // 合并单元格
            $sheet->setCellValue('A'.$row, "日期："); // 单元格填充数据
            $sheet->mergeCells('C'.$row.':H'.$row); // 合并单元格
            $sheet->setCellValue('C'.$row, ""); // 单元格填充数据
            $sheet->mergeCells('O'.$row.':P'.$row); // 合并单元格
            $sheet->setCellValue('O'.$row, "日期："); // 单元格填充数据
            $sheet->mergeCells('Q'.$row.':V'.$row); // 合并单元格
            $sheet->setCellValue('Q'.$row, ""); // 单元格填充数据
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $sheet->getStyle('A'.$row.':'.'AA'.$row)->getAlignment()->setWrapText(true); //长度不够显示的时候是否自动换行

            // 设置字体大小
            $sheet->getStyle('A1:'.'AA'.$row)->getFont()->setSize(8); // 设置字体大小
            $sheet->getStyle('A1:AA1')->getFont()->setSize(14); // 设置字体大小

            $path = '/var/www/online/zity/public/admin/export2/'.$fileName.'.xlsx';
            // 导出
            @ob_clean();
//            if ($fileType == 'xls') {
//                header('Content-Type: application/vnd.ms-excel');
//                header('Cache-Control: max-age=1');
//                header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
//                $objWriter = new \PHPExcel_Writer_Excel5($obj);
////                $objWriter->save('php://output');
////                exit;
//
//                $objWriter->save($path);
//                return ['code' => 200, 'msg' => '获取成功', 'data' => ['path' => 'https://view.officeapps.live.com/op/view.aspx?src=
//'.$path]];
//            } else
            if ($fileType == 'xlsx') {
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Cache-Control: max-age=0');

//                header('Content-Disposition: attachment;filename="' . $fileName . '.pdf');
//                $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'PDF');

                header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
                $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

//                 $objWriter->save('php://output');
                $objWriter->save($path);
                $url = 'http://api.zity.cn/admin/export2/'.$fileName . '.xlsx?id='.time();
                return ['code' => 200, 'msg' => '获取成功', 'data' => ['path' => 'https://view.officeapps.live.com/op/view.aspx?src='.$url]];
            }

            if($fileType=="pdf"){
                $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'PDF');
                $objWriter->setSheetIndex(0);
                header("Pragma: public");
                header("Expires: 0");
                header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
                header("Content-Type:application/force-download");
                header("Content-Type: application/pdf");
                header("Content-Type:application/octet-stream");
                header("Content-Type:application/download");
                header("Content-Disposition:attachment;filename=".$fileName.'.pdf');
                header("Content-Transfer-Encoding:binary");
                $objWriter->save($path);
                $url = 'http://api.zity.cn/admin/export2/'.$fileName . '.xlsx';
                return ['code' => 200, 'msg' => '获取成功', 'data' => ['path' => 'https://view.officeapps.live.com/op/view.aspx?src='.$url]];
            }
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '打印错误！原因：'.$e->getMessage().';错误位置：'.$e->getLine()];
        }
    }

    public function exportPlaceOrderContractDetail($params)
    {
        try {
            if (isset($params['token'])){
                $user = db::table('users')->where('token', $params['token'])
                    ->first();
                if (empty($user)){
                    throw new \Exception('未查询到操作人信息！');
                }
                $params['user_id'] = $user->Id;
            }else{
                throw new \Exception('未给定操作人令牌！');
            }
            if (isset($params['id']) && !empty($params['id'])) {
                $contractMdl = DB::table('cloudhouse_contract_total')->where('id', $params['id'])
                    ->first();
                if (empty($contractMdl)) {
                    throw new \Exception('未查询到该合同信息！');
                }
            } else {
                throw new \Exception('未给定合同标识！');
            }
            $contractDetail = $this->getAmazonPlaceOrderContractDetail(['contract_no' => $contractMdl->contract_no])['data'] ?? [];
            $rule = [];
            foreach ($contractDetail->custom_sku_items as $cus_item){
                $rule[] = $cus_item['size'];
            }
            $rule = array_unique($rule);
            $length = count($rule);
            $width = 9 - $length;
            $priceWidth = 1;
            $memoWidth = 1;
            if ($width > 2){
                if ($width%2 == 1){
                    $priceWidth = bcdiv($width, 2);
                    $memoWidth = bcdiv($width, 2) + 1;
                }elseif ($width%2 == 1){
                    $priceWidth = bcdiv($width, 2);
                    $memoWidth = bcdiv($width, 2);
                }
            }
            switch ($params['print_type']) {
                case 1:
                    $printType = '购销合同-服装范本-打印';
                    $html = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            border-collapse: collapse;
        }
        td, th {
            padding: 0;
        }
        table {
            border-collapse: separate;
            border-spacing: 0;
        }
        td,tr {
            font-size: 9px;
            line-height：9px;
        }
        td{
            width: 5%;
        }
        .border1{
            border: 0.1rem black solid;
            height: 8px;
        }
        .fontBlod{
            font-weight: bold;
        }
        .cell {
            display: flex;
	        justify-content: center;
	        align-items: center;
        }
    </style>
</head>
<body>
    <table   width="100%" cellpadding="2" cellspacing="0">
        <tr>
            <td colspan="20" style="text-align: center;font-size: 20px; font-weight: bold; padding-bottom: 20px;"><div class="cell">'.$contractDetail->company_name.'购销合同</div></td>
        </tr>
        <tr>
            <td colspan="20"></td>
        </tr>
        <tr>
            <td colspan="14"><div class="cell">甲方单位：'.$contractDetail->company_name.'(需方)</div></td>
            <td colspan="6"><div class="cell">合同编号：'.$contractDetail->contract_no.'</div></td>
        </tr>
        <tr>
            <td colspan="14"><div class="cell">乙方单位：'.$contractDetail->supplier_name.'(供方)</div></td>
            <td colspan="6"><div class="cell">签约时间：'.$contractDetail->sign_date.'</div></td>
        </tr>
        <tr>
            <td colspan="14"></td>
            <td colspan="6"><div class="cell">签约地点：'.$contractDetail->signing_location.'</div></td>
        </tr>
        <tr>
            <td colspan="14"></td>
            <td colspan="6"><div class="cell">交期时间：'.$contractDetail->report_date.'</div></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: left; font-weight: bold;"><div class="cell">为促进甲方、乙方双方合作顺利开展，保障双方权益，根据《中华人民共和国民法典》及相关法律法规的规定，经双方友好协商特订立本合同，供共同遵守。</div></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>
        <tr>
            <td colspan="20"><div class="cell">一、 1、甲方商品的款号/品名，数量，单价，金额（人民币）</div></td>
        </tr>

        <tr>
        <td class="border1" colspan="3" rowspan="2" style="text-align: center;"><div class="cell">款号</div></td>
            <td class="border1" colspan="2" rowspan="2" style="text-align: center;"><div class="cell">款式</div></td>
            <td class="border1" colspan="2" rowspan="2" style="text-align: center;"><div class="cell">品名</div></td>
            <td class="border1" colspan="'.($length+1).'" rowspan="1" style="text-align: center;"><div class="cell">颜色尺码</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">合计(件/套)</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">单价(元)(含税)</div></td>
            <td class="border1" colspan="'.$priceWidth.'" rowspan="2" style="text-align: center;"><div class="cell">金额(含税)</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">吊牌</div></td>
            <td class="border1" colspan="'.$memoWidth.'" rowspan="2" style="text-align: center;"><div class="cell">备注</div></td>
        </tr>';

                    $html .= '<tr>
            <td class="border1" colspan="1" rowspan="1" style="text-align: center;">颜色</td>';

                    foreach ($rule as $size){
                        $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.$size.'</td>';
                    }

                    $html .= '
        </tr>';

                    $contractSpu = $contractDetail->spu_items;
                    $sizeInfo = [];
                    $totalPrice = 0;
                    foreach ($contractSpu as $v){
                        $html .= '<tr>
                <td class="border1" colspan="3" style="text-align: center;">'.$v['spu'].'</td>
                <td class="border1" colspan="2" style="text-align: center;"><img src="' . $v['img'] . '" width="70pt"></td>
                <td class="border1" colspan="2" style="text-align: center;">'.$v['title'].'</td>
                <td class="border1" colspan="1" style="text-align: center;">'.$v['color_name'].'/'.$v['color_identifying'].'</td>';
                        $numInfo = $v['num_info'];
                        foreach ($rule as $size){
                            $num = $numInfo->$size ?? 0;
                            if (isset($sizeInfo[$size])){
                                $sizeInfo[$size] += $num;
                            }else{
                                $sizeInfo[$size] = $num;
                            }
                            $totalPrice += $v['one_price'] * $num;
                            $html .= '<td class="border1" colspan="1" style="text-align: center;">'.$num.'</td>';
                        }
                $html .= '<td class="border1" colspan="1" rowspan="1" style="text-align: center;"><div class="cell">'.$v['count'].'</div></td>
                <td class="border1" colspan="1" rowspan="1" style="text-align: center;"><div class="cell">'.$v['one_price'].'</div></td>
                <td class="border1" colspan="'.$priceWidth.'" rowspan="1" style="text-align: center;"><div class="cell">'.$v['price'].'</div></td>
                <td class="border1" colspan="1" style="text-align: center;">'.$contractDetail->brand.'</td>
                <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;">'.$v['memo'].'</td>
            </tr>';
                    }
                    $html .= '<tr>
            <td class="border1" colspan="7" style="text-align: center;">合计金额</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>';
                    foreach ($rule as $size){
                        $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.$sizeInfo[$size].'</td>';
                    }

                    $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.array_sum($sizeInfo).'</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>
            <td class="border1" colspan="'.$priceWidth.'" style="text-align: center;">'.$this->floorDecimal($totalPrice).'</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>
            <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;"></td>
        </tr>';
                    $count = 4;
                    $payment_information = $contractDetail->payment_information;
                    if ($count < count($payment_information)){
                        $count = count($payment_information);
                    }
                    for ($i = 0; $i < $count; $i++){
                        $html .= '<tr>
                <td class="border1" colspan="7" style="text-align: center;">'.$payment_information[$i]['title'].'</td>
                <td class="border1" colspan="1" style="text-align: center;"></td>';

                        foreach ($rule as $size){
                            $html .= '<td class="border1" colspan="1" style="text-align: center;"></td>';
                        }

                $html .= '
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="'.$priceWidth.'" style="text-align: center;">'.$payment_information[$i]['money'].'</td>
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;"></td>
            </tr>';
                    }

                    $html .= '<tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>

        <tr>
            <td colspan="20">2、需提供产前确认样（拍照样）齐色码'.implode('、', $rule).'各一件。</td>
        </tr>

        <tr>
            <td colspan="20">3、出货良品率保持99%，按合同规定的交货期交货，若逾期大于8天以上的，延一天按万分之7.5扣款，≥31天 除了扣款还需承担甲方运费。</td>
        </tr>
        <tr>
            <td colspan="20">（如有其他原因延期交货，双方友好协商交货日期，并以书面或者邮件给以通知，须甲方同意为准，不可延期后再进行延期补签申请）。</td>
        </tr>

        <tr>
            <td colspan="20">二、质量要求技术标准、乙方对质量负责的条件:</td>
        </tr>
        <tr>
            <td colspan="20">1、产品质量和材料以需方提供的原样一致及双方最终签章确认产前样为准！如有不一致，甲方有权取消本次合同。</td>
        </tr>
        <tr>
            <td colspan="20">2、必须符合国家法定商检标准及甲方提出的质量标准,按照AQL2.5质量标准进行验货。</td>
        </tr>
        <tr>
            <td colspan="20">三、交货地点、方式及运输费用</td>
        </tr>
        <tr>
            <td colspan="20">1、须按甲方提供的交货期及指定的地点交货，我方地址分别为：厦门同安仓、泉州仓、厦门软二仓。</td>
        </tr>
        <tr>
            <td colspan="20">2、乙方按甲方指定地点送货，在保证交货期情况下乙方可自主选择运输方式，运输费用乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">四、包装标准：按我司要求包装（详细按理单资料）</td>
        </tr>
        <tr>
            <td colspan="20">五、验收标准、方法及提出异议期限：</td>
        </tr>
        <tr>
            <td colspan="20">1、甲方派出的QC以确认样和国家法定商检标准为准，对产品的品质、规格、数量、包装等外观质检验。乙方须严格按甲方要求执行。</td>
        </tr>
        <tr>
            <td colspan="20">2、 按确认样和制作单要求生产。乙方未能按质按量按时交货引起的损失，概由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">3、甲方在收货后有权对因工厂生产技术、材料等方面造成的质量问题提出索赔、严重者可提出退货及索赔，乙方应予以接受。</td>
        </tr>
        <tr>
            <td colspan="20">六、货款的计算及结算方式：</td>
        </tr>
        <tr>
            <td colspan="20">1、付款方式：T/T</td>
        </tr>';

                    $html .= '
        <tr>
            <td colspan="20">'.$contractMdl->payment_settlement_method.'</td>
        </tr>';

                    $html .= '<tr>
            <td colspan="20">七、违约责任：</td>
        </tr>
        <tr>
            <td colspan="20">2、乙方所交货品与本合同规定质量不符导致甲方在转售该批服装时被客人拒绝接收或降价或其它救济方式时，甲方有权对乙方采取相应的措施，乙方不得拒绝。</td>
        </tr>
        <tr>
            <td colspan="20">3、因乙方不能按期交货，甲方不同意延期所引起的各项运费或制约款等费用由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">八、解决合同纠纷方式：</td>
        </tr>
        <tr>
            <td colspan="20">合同履行过程中若发生纠纷，经友好协商未果提起诉讼，由签约地（厦门思明区）法院管辖。</td>
        </tr>
        <tr>
            <td colspan="20">九、其它约定事项:</td>
        </tr>
        <tr>
            <td colspan="20">1、由甲方提供的理单资料（即大货要求）均为本合同附件，其它未尽事宜可经双方商定进行书面修改补充并视为本合同不可分割的部分，同样具有法律效力。</td>
        </tr>
        <tr>
            <td colspan="20">2、大货材料必须由甲方确认后才可生产，否则由此引起的责任及后果由乙方承担;</td>
        </tr>
        <tr>
            <td colspan="20">3、甲方品牌产品、组合方式、设计款式、包装方式等待均不可销售其他电商卖家。如发现乙方向其他电商卖家销售以上规定的产品造成甲方损失应由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">4、如果是因为乙方质量等原因，造成甲方派QC前往乙方工厂验货超过2次的，所产生的验货费用由乙方承担。 （根据验货地点费用起：500元-1000元以上）</td>
        </tr>
        <tr>
            <td colspan="20">5、乙方须在交货前免费提供符合甲方质量要求的初样，修改样，产前样，大货样，若不符合要求，须重新提供。</td>
        </tr>
        <tr>
            <td colspan="20">6、乙方必须做产前样给甲方确认后，方可开裁&生产大货，否则后果将由乙方负全部责任。</td>
        </tr>
        <tr>';
                    if ($contractDetail->contract_class == 5){
                        $html .= '
            <td colspan="4">外发加工合同号：</td>
            <td colspan="6">'.$contractDetail->process_contract_no.'</td>
            <td colspan="4">外发加工工厂：</td>
            <td colspan="6">'.$contractDetail->process_supplier_name.'</td>
                        ';
                    }
        $html .= '
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="2">甲方单位：</td>
            <td colspan="8">'.$contractDetail->company_name.'</td>
            <td colspan="2">乙方单位：</td>
            <td colspan="8">'.$contractDetail->supplier_name.'</td>
        </tr>
        <tr>
            <td colspan="2">地址：</td>
            <td colspan="8">'.$contractDetail->company_address.'</td>
            <td colspan="2">地址：</td>
            <td colspan="8">'.$contractDetail->supplier_address.'</td>
        </tr>
        <tr>
            <td colspan="10">甲方代表：'.$contractDetail->maker_name.'</td>
            <td colspan="10">乙方代表：</td>
        </tr>
        <tr>
            <td colspan="10">签章：</td>
            <td colspan="10">签章：</td>
        </tr>
        <tr>
            <td colspan="10">日期：'.$contractDetail->sign_date.'</td>
            <td colspan="10">日期：'.$contractDetail->sign_date.'</td>
        </tr>
    </table>
</body>
</html>';
                    break;
                case 2:
                    // 铁艺范本
                    $a = 1;
                    $html = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            border-collapse: collapse;
        }
        td, th {
            padding: 0;
        }
        table {
            border-collapse: separate;
            border-spacing: 0;
        }
        td,tr {
            font-size: 9px;
            line-height：9px;
        }
        td{
            width: 5%;
        }
        .border1{
            border: 0.1rem black solid;
            height: 8px;
        }
        .fontBlod{
            font-weight: bold;
        }
        .cell {
            display: flex;
	        justify-content: center;
	        align-items: center;
        }
    </style>
</head>
<body>
    <table   width="100%" cellpadding="2" cellspacing="0">
        <tr>
            <td colspan="20" style="text-align: center;font-size: 20px; font-weight: bold; padding-bottom: 20px;"><div class="cell">'.$contractDetail->company_name.'购销合同</div></td>
        </tr>
        <tr>
            <td colspan="20"></td>
        </tr>
        <tr>
            <td colspan="14"><div class="cell">甲方单位：'.$contractDetail->company_name.'</div></td>
            <td colspan="6"><div class="cell">合同编号：'.$contractDetail->contract_no.'</div></td>
        </tr>
        <tr>
            <td colspan="14"><div class="cell">乙方单位：'.$contractDetail->supplier_name.'</div></td>
            <td colspan="6"><div class="cell">签约时间：'.$contractDetail->sign_date.'</div></td>
        </tr>
        <tr>
            <td colspan="14"></td>
            <td colspan="6"><div class="cell">签约地点：'.$contractDetail->signing_location.'</div></td>
        </tr>
        <tr>
            <td colspan="14"></td>
            <td colspan="6"><div class="cell">交期时间：'.$contractDetail->report_date.'</div></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: center; font-weight: bold;"><div class="cell">依照国家有关法律法规，签约双方就采购出口货物有关事项协商一致，达成本合同。</div></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>
        <tr>
            <td colspan="20"><div class="cell">一、 1、甲方商品的款号/品名，数量，单价，金额（人民币）</div></td>
        </tr>

        <tr>
        <td class="border1" colspan="3" rowspan="2" style="text-align: center;"><div class="cell">款号</div></td>
            <td class="border1" colspan="2" rowspan="2" style="text-align: center;"><div class="cell">款式</div></td>
            <td class="border1" colspan="2" rowspan="2" style="text-align: center;"><div class="cell">品名</div></td>
            <td class="border1" colspan="'.($length+1).'" rowspan="1" style="text-align: center;"><div class="cell">颜色尺码</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">合计(件/套)</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">单价(元)(含税)</div></td>
            <td class="border1" colspan="'.$priceWidth.'" rowspan="2" style="text-align: center;"><div class="cell">金额(含税)</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">吊牌</div></td>
            <td class="border1" colspan="'.$memoWidth.'" rowspan="2" style="text-align: center;"><div class="cell">备注</div></td>
        </tr>';

                    $html .= '<tr>
            <td class="border1" colspan="1" rowspan="1" style="text-align: center;">颜色</td>';

                    foreach ($rule as $size){
                        $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.$size.'</td>';
                    }

                    $html .= '
        </tr>';

                    $contractSpu = $contractDetail->spu_items;
                    $sizeInfo = [];
                    $totalPrice = 0;
                    foreach ($contractSpu as $v){
                        $html .= '<tr>
                <td class="border1" colspan="3" style="text-align: center;">'.$v['spu'].'</td>
                <td class="border1" colspan="2" style="text-align: center;"><img src="' . $v['img'] . '" width="70pt"></td>
                <td class="border1" colspan="2" style="text-align: center;">'.$v['title'].'</td>
                <td class="border1" colspan="1" style="text-align: center;">'.$v['color_name'].'/'.$v['color_identifying'].'</td>';
                        $numInfo = $v['num_info'];
                        foreach ($rule as $size){
                            $num = $numInfo->$size ?? 0;
                            if (isset($sizeInfo[$size])){
                                $sizeInfo[$size] += $num;
                            }else{
                                $sizeInfo[$size] = $num;
                            }
                            $totalPrice += $v['one_price'] * $num;
                            $html .= '<td class="border1" colspan="1" style="text-align: center;">'.$num.'</td>';
                        }
                        $html .= '<td class="border1" colspan="1" rowspan="1" style="text-align: center;"><div class="cell">'.$v['count'].'</div></td>
                <td class="border1" colspan="1" rowspan="1" style="text-align: center;"><div class="cell">'.$v['one_price'].'</div></td>
                <td class="border1" colspan="'.$priceWidth.'" rowspan="1" style="text-align: center;"><div class="cell">'.$v['price'].'</div></td>
                <td class="border1" colspan="1" style="text-align: center;">'.$contractDetail->brand.'</td>
                <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;">'.$v['memo'].'</td>
            </tr>';
                    }
                    $html .= '<tr>
            <td class="border1" colspan="7" style="text-align: center;">合计金额</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>';
                    foreach ($rule as $size){
                        $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.$sizeInfo[$size].'</td>';
                    }

                    $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.array_sum($sizeInfo).'</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>
            <td class="border1" colspan="'.$priceWidth.'" style="text-align: center;">'.$this->floorDecimal($totalPrice).'</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>
            <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;"></td>
        </tr>';
                    $count = 4;
                    $payment_information = $contractDetail->payment_information;
                    if ($count < count($payment_information)){
                        $count = count($payment_information);
                    }
                    for ($i = 0; $i < $count; $i++){
                        $html .= '<tr>
                <td class="border1" colspan="7" style="text-align: center;">'.$payment_information[$i]['title'].'</td>
                <td class="border1" colspan="1" style="text-align: center;"></td>';

                        foreach ($rule as $size){
                            $html .= '<td class="border1" colspan="1" style="text-align: center;"></td>';
                        }

                        $html .= '
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="'.$priceWidth.'" style="text-align: center;">'.$payment_information[$i]['money'].'</td>
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;"></td>
            </tr>';
                    }

                    $html .= '<tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>

        <tr>
            <td colspan="2">品牌：</td>
            <td colspan="8"></td>
            <td colspan="10">，需提供产前确认样（拍照样）齐色码数各一件</td>
        </tr>

        <tr>
            <td colspan="20">出货良品率保持99%，按合同规定的交货期交货，若逾期大于8天以上的，延一天按万分之7.5扣款，≥31天除了扣款还需承担空运费。</td>
        </tr>
        <tr>
            <td colspan="20">（如有其他原因延期交货，双方友好协商交货日期，并以书面或者邮件申请，甲方同意为准，不可延期后再进行延期补签申请）</td>
        </tr>

        <tr>
            <td colspan="20">二、质量要求技术标准、乙方对质量负责的条件: </td>
        </tr>
        <tr>
            <td colspan="20">产品质量和材料以需方提供的原样一致及双方最终签章确认产前样为准！如有不一致，甲方有权取消合同。 符合国家法定商检标准及甲方提出的质量标准,按照AQL2.5质量标准进行验货。</td>
        </tr>
        <tr>
            <td colspan="20">三、交货地点、方式及运输费用</td>
        </tr>
        <tr>
            <td colspan="20">1、按甲方提供的交货期及指定的地点交货，送货地址：厦门同安仓、泉州仓</td>
        </tr>
        <tr>
            <td colspan="20">2、乙方按甲方指定地点送货，在保证交货期情况下乙方可自主选择运输方式，运输费用乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">四、包装标准：按我司要求包装（详细按理单资料）</td>
        </tr>
        <tr>
            <td colspan="20">五、验收标准、方法及提出异议期限：</td>
        </tr>
        <tr>
            <td colspan="20">1、甲方派出的QC以确认样和国家法定商检标准为准，对产品的品质、规格、数量、包装等外观质检验。乙方须严格按确认样和制作单要求生产。乙方未能按质按量按时交货引起的损失，概由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">2、甲方在收货后90天内有权对因工厂生产技术、材料等方面造成的质量问题提出索赔、严重者可提出退货及索赔，乙方应予接受。</td>
        </tr>
        <tr>
            <td colspan="20">六、货款的计算及结算方式：</td>
        </tr>
        <tr>
            <td colspan="20">1、付款方式：</td>
        </tr>';

        $html .= '
        <tr>
            <td colspan="20">付款方式：'.$contractMdl->payment_settlement_method.'</td>
        </tr>';

        $html .= '<tr>
            <td colspan="20">七、违约责任：</td>
        </tr>
        <tr>
            <td colspan="20">1、乙方所交货品与本合同规定质量不符导致甲方在转售该批服装时被客人拒绝接收或降价或其它救济方式时，甲方有权对乙方采取相应的措施，乙方不得拒绝。</td>
        </tr>
        <tr>
            <td colspan="20">2、因乙方不能按期交货，甲方不同意延期所引起的空运费或制约款等费用由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">八、解决合同纠纷方式：</td>
        </tr>
        <tr>
            <td colspan="20">合同履行过程中若发生纠纷，经友好协商未果提起诉讼，由签约地法院管辖。</td>
        </tr>
        <tr>
            <td colspan="20">九、其它约定事项:</td>
        </tr>
        <tr>
            <td colspan="20">1、由甲方提供的理单资料（即大货要求）均为本合同附件，其它未尽事宜可经双方商定进行书面修改补充并视为本合同不可分割的部分，同样具有法律效力。</td>
        </tr>
        <tr>
            <td colspan="20">2、大货材料必须由甲方确认后才可生产，否则由此引起的责任及后果由乙方承担;</td>
        </tr>
        <tr>
            <td colspan="20">3、我司品牌产品、组合方式、设计款式、包装方式等待均不可销售其他电商卖家。如发现贵司向其他电商卖家销售以上规定的产品造成我司损失应由贵司承担。</td>
        </tr>
        <tr>
            <td colspan="20">4、如果是因为乙方质量等原因，造成甲方派QC前往乙方工厂验货超过2次的，所产生的费用由乙方承担。 （根据验货地点费用起：500元-1000元以上）</td>
        </tr>
        <tr>
            <td colspan="20">6、乙方必须做产前样给甲方确认后，方可开裁&生产大货，否则后果将由乙方负全部责任。</td>
        </tr>
       <tr>';
                    if ($contractDetail->contract_class == 5){
                        $html .= '
            <td colspan="4">外发加工合同号：</td>
            <td colspan="6">'.$contractDetail->process_contract_no.'</td>
            <td colspan="4">外发加工工厂：</td>
            <td colspan="6">'.$contractDetail->process_supplier_name.'</td>
                        ';
                    }
                    $html .= '
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="2">甲方单位：</td>
            <td colspan="8">'.$contractDetail->company_name.'</td>
            <td colspan="2">乙方单位：</td>
            <td colspan="8">'.$contractDetail->supplier_name.'</td>
        </tr>
        <tr>
            <td colspan="2">地址：</td>
            <td colspan="8">'.$contractDetail->company_address.'</td>
            <td colspan="2">地址：</td>
            <td colspan="8">'.$contractDetail->supplier_address.'</td>
        </tr>
        <tr>
            <td colspan="10">甲方代表：'.$contractDetail->maker_name.'</td>
            <td colspan="10">乙方代表：</td>
        </tr>
        <tr>
            <td colspan="10">签章：</td>
            <td colspan="10">签章：</td>
        </tr>
        <tr>
            <td colspan="10">日期：'.$contractDetail->sign_date.'</td>
            <td colspan="10">日期：'.$contractDetail->sign_date.'</td>
        </tr>
    </table>
</body>
</html>';
                    $printType = '购销合同-铁艺范本-打印';
                    break;
            }
            // 加入队列
//            $result = $this->publicSavePdf($html, '购销合同', $contractMdl->contract_no, $printType, $params['user_id']);
//            if ($result['code'] == 500){
//                throw new \Exception($result['msg']);
//            }
            $path = $this->getSavePdfPath($html, '购销合同', $contractMdl->contract_no);
            if (empty($path)){
                throw  new \Exception('未获取到路径！');
            }

            return ['code' => 200, 'msg' => '打印成功！', 'data' => $path];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function curls($url, $post=false, $head=''){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址

        // 优化curl 速度
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
        curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);//强制使用IPV4协议解析域名
        // 头部
        if(!empty($head)){
//			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //头部要送出'Expect: '
            curl_setopt($curl, CURLOPT_HTTPHEADER, $head); // 请求头部
        }

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if(!empty($post)){
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 120); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作

        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $res; // 返回数据，json格式
    }

//    public function httpcopy($url){
//        $remote_pdf_url = $url;
//        $remote_pdf_url = urldecode($remote_pdf_url);
//        $file_name = basename($remote_pdf_url);
//
//        $local_path = './pdf/'.$file_name.'.pdf';
//        if (file_exists($local_path)) {
//            return $local_path;
//        }
//
//        // 下载远程 PDF 文件并保存到本地服务器
//        $file_content = file_get_contents($remote_pdf_url);
//        if ($file_content !== false) {
//            file_put_contents($local_path, $file_content);
//            return $local_path;
//        } else {
//            echo '下载 PDF 文件失败。';
//        }
//    }

//    public function httpcopy($url, $file="/test.jpg",$timeout=60) {
//        $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
//        $dir = pathinfo($file,PATHINFO_DIRNAME);
//        !is_dir($dir) && @mkdir($dir,0755,true);
//        $url = str_replace(" ","%20",$url);
//
//        if(function_exists('curl_init')) {
//            $ch = curl_init();
//            curl_setopt($ch, CURLOPT_URL, $url);
//            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//            $temp = curl_exec($ch);
//            try {
//                file_put_contents($file, $temp);
//            } catch (\Throwable $th) {
//                // var_dump($th);
//                return ['err' => true, 'data' => $th->getMessage()];
//            }
//
//            if (@file_put_contents($file, $temp) && !curl_error($ch)) {
//                //     $tofile = "/www/data/online/new_zity_php/public/admin/excel_img/".$newname;
//
//                //     rename($file,$tofile);
//
//
//                //    $url = "/admin/excel_img/".$newname;
//                return ['err' => false, 'data' => $file];
//            } else {
//                return ['err' => true, 'data' => '下载远程图片失败'];
//            }
//        }
//    }

    public function getHistorySpuPrice($params)
    {
        try{
            $list = db::table('cloudhouse_contract as a')
                ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
                ->leftJoin('suppliers as c', 'c.Id', '=', 'b.supplier_id')
                ->leftJoin('self_spu_info as d', 'a.spu_id', '=', 'd.spu_id')
                ->whereIn('contract_class', [0, 1, 2, 5])
                ->where('b.contract_status', 2);
            if (!isset($params['spu_id']) || empty($params['spu_id'])){
                throw new \Exception("未给定Spu标识!");
            }
            if (!isset($params['color_identifying']) || empty($params['color_identifying'])){
                throw new \Exception("未给定颜色标识!");
            }

            $list = $list->where('a.spu_id', $params['spu_id'])
                ->where('a.color_identifying', $params['color_identifying']);
//            if (isset($params['type']) && $params['type'] == 1){
//                $list = $list->where('contract_class', '<>', 5);
//            }
//            if (isset($params['type']) && $params['type'] == 2){
//                $list = $list->where('contract_class', 5);
//            }
            $count = $list->count();
            $list = $list->orderBy('a.create_time', 'ASC')
                ->get(['a.*', 'c.name as supplier_name', 'b.contract_class', 'd.unit_price']);

            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    $params['user_id'] = $users->Id ?? 0;
                }else{
                    $params['user_id'] = 0;
                }
            }
            $controller = new Controller();
            $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['product_contract_price']]);

            foreach ($list as $v){
                $v->contract_class_name = Constant::CONTRACT_CLASS[$v->contract_class] ?? '艾诺科合同';
                $contractPrice = $v->one_price ?? 0.00;
//                $salesOrderPrice = $contractPrice * 1.15;
//                $outgoingPrice = $contractPrice * 1.09 * 1.19;
//                $v->sales_price = '无权查看';
//                $v->outgoing_price = '无权查看';
                if (!$power['product_contract_price']){
                    $v->one_price = '无权查看';
                    $v->unit_price = '无权查看';
                }
                $v->unit_price = '';
//                if ($power['show_product_sales_order_price']) {
//                    $v->sales_price = $this->floorDecimal($salesOrderPrice);
//                }
//                if ($power['show_product_outgoing_price']) {
//                    $v->outgoing_price = $this->floorDecimal($outgoingPrice);
//                }
            }

            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }

    }

    public function additionalRecordingContract($params)
    {
        try {
//            throw new \Exception('该功能待维护，暂停使用！');
            // 获取所有请求参数
            $file = $params['file'];
            if (empty($file)){
                throw new \Exception( '导入失败，文件为空！');
            }

            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }

            //获取文件后缀名
            $extension = $file->getClientOriginalExtension();
            if ($extension == 'csv') {
                $PHPExcel = new \PHPExcel_Reader_CSV();
            } elseif ($extension == 'xlsx') {
                $PHPExcel = new \PHPExcel_Reader_Excel2007();
            } else {
                $PHPExcel = new \PHPExcel_Reader_Excel5();
            }

            if (!$PHPExcel->canRead($file)) {
                throw new \Exception( '导入失败，Excel文件错误');
            }
            $PHPExcelLoad = $PHPExcel->load($file);

            $Sheet = $PHPExcelLoad->getSheet(0);
            /**取得一共有多少行*/
            $allRow = $Sheet->getHighestRow();

            $allRow = $allRow + 1;
            //循环插入流量数据
            $i = 0;

//            if(!(isset($params['warehouse_name']) && !empty($params['warehouse_name']))){
//                throw new \Exception( '导入失败，缺少仓库名称', 400);
//            }

            // 打印未查询到的sku
            $emptySku = array();
            DB::beginTransaction();
            // 循环处理数据变更
            $customSkuArr = [];
            $spuArr = [];
            $totalNum = 0;
            $totalPrice = 0;
            $spuNum = 0;
            $baseModel = new BaseModel();
            $error = '';
            for ($j = 2; $j < $allRow; $j++) {
                // 获取格式化值
                $spu = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue()) ?? '';
                $brand = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue()) ?? '';
                $color = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue()) ?? '';
                $XXSNum = $Sheet->getCellByColumnAndRow(3, $j)->getValue() ?? 0;
                $XSNum = $Sheet->getCellByColumnAndRow(4, $j)->getValue() ?? 0;
                $SNum = $Sheet->getCellByColumnAndRow(5, $j)->getValue() ?? 0;
                $MNum = $Sheet->getCellByColumnAndRow(6, $j)->getValue() ?? 0;
                $LNum = $Sheet->getCellByColumnAndRow(7, $j)->getValue() ?? 0;
                $XLNum = $Sheet->getCellByColumnAndRow(8, $j)->getValue() ?? 0;
                $XXLNum = $Sheet->getCellByColumnAndRow(9, $j)->getValue() ?? 0;
                $XXXLNum = $Sheet->getCellByColumnAndRow(10, $j)->getValue() ?? 0;
                $XXXXLNum = $Sheet->getCellByColumnAndRow(11, $j)->getValue() ?? 0;
                $XXXXXLNum = $Sheet->getCellByColumnAndRow(12, $j)->getValue() ?? 0;
                $XXXXXXLNum = $Sheet->getCellByColumnAndRow(13, $j)->getValue() ?? 0;
                $XXXXXXXLNum = $Sheet->getCellByColumnAndRow(14, $j)->getValue() ?? 0;
                $XXXXXXXXLNum = $Sheet->getCellByColumnAndRow(15, $j)->getValue() ?? 0;
                $supplierName = $Sheet->getCellByColumnAndRow(16, $j)->getValue() ?? '';
                $supplierNo = $Sheet->getCellByColumnAndRow(17, $j)->getValue() ?? '';
                $price = $Sheet->getCellByColumnAndRow(18, $j)->getValue() ?? 0.00;
                $companyName = $Sheet->getCellByColumnAndRow(19, $j)->getValue() ?? '思科迪电子商务有限公司';
                $contractType = $Sheet->getCellByColumnAndRow(20, $j)->getValue() ?? '委托加工';

                if (empty($spu)){
                    $error .= '第'.$j.'行未给定spu！';
                }
                if (empty($color)){
                    $error .= '第'.$j.'行未给定颜色标识！';
                }
                if ($price < 0){
                    $error .= '第'.$j.'单价不能小于0！';
                }
                $supplierId = 0;
                if (!empty($supplierNo)){
                    $supplierMdl = db::table('suppliers')->where('supplier_no', $supplierNo)->first();
                    if (!empty($supplierMdl)){
                        $supplierName = $supplierMdl->short_name;
                        $supplierId = $supplierMdl->Id;
                        $supplierNo = $supplierMdl->supplier_no;
                    }
                }else{
                    if (!empty($supplierName)){
                        $supplierMdl = db::table('suppliers')->where('name', $supplierName)->first();
                        if (!empty($supplierMdl)){
                            $supplierName = $supplierMdl->short_name;
                            $supplierId = $supplierMdl->Id;
                            $supplierNo = $supplierMdl->supplier_no;
                        }
                    }
                }
                $companyMdl = db::table('company')
                    ->where('company_name', $companyName)
                    ->first();
                $companyId = $companyMdl->id ?? 0;
                $color = explode('/', $color);
                $colorCode = $color[1];
                $colorName = $color[0];
                $spuId = $baseModel->GetSpuId($spu);
                $spuMdl = $baseModel->GetSpu($spuId);
                $colorMdl = db::table('self_color_size')->where('identifying', $colorCode)->first();
                if ($XXSNum){
                    $size = 'XXS';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXSNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XSNum){
                    $size = 'XS';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XSNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($SNum){
                    $size = 'S';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $SNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($MNum){
                    $size = 'M';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $MNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($LNum){
                    $size = 'L';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $LNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XLNum){
                    $size = 'XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XXLNum){
                    $size = '2XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XXXLNum){
                    $size = '3XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXXLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XXXXLNum){
                    $size = '4XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXXXLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XXXXXLNum){
                    $size = '5XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXXXXLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XXXXXXLNum){
                    $size = '6XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXXXXXLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XXXXXXXLNum){
                    $size = '7XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXXXXXXLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                if ($XXXXXXXXLNum){
                    $size = '8XL';
                    $customSkuMdl = db::table('self_custom_sku')->where('spu_id', $spuId)->where('color_id', $colorMdl->id ?? 0)->where('size', $size)->first();
                    if (!empty($customSkuMdl)){
                        $customSkuArr[] = [
                            'spu' => $spu,
                            'spu_id' => $spuId,
                            'custom_sku' => $customSkuMdl->custom_sku ?? '',
                            'custom_sku_id' => $customSkuMdl->id ?? 0,
                            'size' => $size,
                            'num' => $XXXXXXXXLNum,
                            'price' => $price,
                            'color' => $colorCode,
                            'color_name' => $colorName,
                            'color_name_en' => $colorMdl->english_name,
                            'name' => $customSkuMdl->name ?? '',
                        ];
                    }
                }
                $spuCount = $XXSNum + $XSNum + $SNum + $MNum + $LNum + $XLNum + $XXLNum + $XXXLNum + $XXXXLNum + $XXXXXLNum + $XXXXXXLNum + $XXXXXXXLNum + $XXXXXXXXLNum;
                $allPrice = bcmul($spuCount, $price, 2);
                $spuArr[] = [
                    'spu' => $spu,
                    'spu_id' => $spuId,
                    'title' => '',
                    'count' => $spuCount,
                    'one_price' => $price,
                    'price' => $spuCount * $price,
                    'report_date' => date('Y-m-d'),
                    'type' => 1,
                    'XXS' => $XXSNum,
                    'XS' => $XSNum,
                    'S' => $SNum,
                    'M' => $MNum,
                    'L' => $LNum,
                    'XL' => $XLNum,
                    '2XL' => $XXLNum,
                    '3XL' => $XXXLNum,
                    '4XL' => $XXXXLNum,
                    '5XL' => $XXXXXLNum,
                    '6XL' => $XXXXXXLNum,
                    '7XL' => $XXXXXXXLNum,
                    '8XL' => $XXXXXXXXLNum,
                    'sign_date' => date('Y-m-d'),
                    'create_time' => date('Y-m-d H:i:s', microtime(true)),
                    'color_identifying' => $colorCode,
                    'color_name' =>$colorName,
                ];
                $totalPrice += $allPrice;
                $totalNum += $spuCount;
                $spuNum += 1;
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            $contractNo = $this->idBuilder->createId('AMAZON_PLACE_ORDER_CONTRACT_CODE_VIRTUAL');
            $contractData = [
                'total_count' => $totalNum,
                'total_price' => $totalPrice,
                'spu_count' => $spuNum,
                'report_date' => date('Y-m-d'),
                'sign_date' => date('Y-m-d'),
                'contract_type' => $contractType,
                'spu_count' => $spuNum,
                'supplier_short_name' => $supplierName,
                'supplier_id' => $supplierId,
                'contract_status' => 2,
                'is_end' => 1,
                'maker_id' => $params['user_id'],
                'input_user_id' => $params['user_id'],
                'company_id' => $companyId,
                'company_name' => $companyName,
                'delivery_location' => '厦门', // 交货地点
                'signing_location' => '厦门', // 签约地点
                'contract_class' => 1,// 合同类别
                'supplier_no' => $supplierNo,
                'contract_no' => $contractNo,
                'contract_class' => 4,
                'brand' => $brand,
                'create_time' => date('Y-m-d H:i:s'),
            ];
            $contractId = db::table('cloudhouse_contract_total')->insertGetId($contractData);
            if (empty($contractId)){
                throw new \Exception('合同保存失败！');
            }
            foreach ($spuArr as &$item){
                $item['contract_no'] = $contractNo;
                $contractSpu = db::table('cloudhouse_contract')->insertGetId($item);
                if (empty($contractSpu)){
                    throw new \Exception('合同Spu保存失败！');
                }
            }
            foreach ($customSkuArr as &$item){
                $item['contract_no'] = $contractNo;
                $contractCustomSku = db::table('cloudhouse_custom_sku')->insertGetId($item);
                if (empty($contractSpu)){
                    throw new \Exception('合同Sku保存失败！');
                }
            }

            DB::commit();

            return ['code' => 200, 'msg' => '导入成功！合同号为：'.$contractNo];
        }catch (\Exception $e){
            DB::rollback();
            return ['code' => 500, 'msg' => '导入失败！'.$e->getMessage().';'.$e->getLine()];
        }
    }

    public function bindPurchaseOrderNo($params)
    {
        $contractNo = array_column($params, 'contract_no');

        $contractList = DB::table('cloudhouse_contract_total')
            ->select(['contract_no'])
            ->whereIn('contract_no', $contractNo)
            ->where('contract_class', 3)
            ->where('contract_status', 2)
            ->get()
            ->pluck('contract_no');


        $denyContractNo = [];//不存在的合同号或者未审批通过的合同号
        $job = new \App\Http\Controllers\Jobs\AlibabaJobController;

        foreach ($params as $param) {
            if (!$contractList->contains($param['contract_no'])) {
                $denyContractNo[] = $param['contract_no'];
                continue;
            }
            DB::table('cloudhouse_contract_total')
                ->where('contract_no', $param['contract_no'])
                ->update([
                    'purchase_order_no' => $param['purchase_order_no'],
                ]);

            $job::runJob(['order_id' => $param['purchase_order_no']]);

        }

        if ($denyContractNo) {
            return ['code' => 500, 'msg' => '绑定失败的合同号：' . implode(',', $denyContractNo)];
        }
        return ['code' => 200, 'msg' => '绑定成功'];
    }

    public function oneClickCompletionContract($params)
    {
//        return ['code' => 500, 'msg' => '该功能调整中，暂停使用！如有需要，请联系it人员。'];
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            $controller = new Controller();
            $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['completion_contract']]);

            if (!$power['completion_contract']){
                throw new \Exception('无完结合同权限，不可操作！');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('id', $params['id'])
                ->get()
                ->keyBy('id');
            $error = '';
            foreach($params['id'] as $k => $id){
                $contract = $contractMdl[$id] ?? [];
                if (!empty($contract)){
                    if ($contract->contract_status != 2){
                        $error .= '第'.($k+1).'行,合同号：'.$contract->contract_no.'合同状态审核非通过状态，不可进行完结操作！';
                        continue;
                    }
                    if ($contract->is_end == 1){
                        $error .= '第'.($k+1).'行,合同号：'.$contract->contract_no.'合同已完结，不可进行完结操作！';
                        continue;
                    }
                    $update = db::table('cloudhouse_contract_total')
                        ->where('id', $id)
                        ->update(['is_end' => 1]);
                    if (empty($update)){
                        $error .= '第'.($k+1).'行,合同号：'.$contract->contract_no.'数据无变化， 完结操作失败!';
                    }
                }else{
                    $error .= '第'.($k+1).'行合同不存在！';
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }

            return ['code' => 200, 'msg' => '一键完结操作成功！'];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '一键完结操作失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }

    }

    public function getCompanyList($params)
    {
        $companyMdl = db::table('company');

        if (isset($params['company_name'])){
            $companyMdl = $companyMdl->where('company_name', 'like', '%'.$params['company_name'].'%');
        }

        $count = $companyMdl->count();

        if (isset($params['page']) || isset($params['limit'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $companyMdl = $companyMdl->limit($limit)->offset($offsetNum);
        }

        $companyMdl = $companyMdl->get();

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $companyMdl]];
    }

    public function getFormatContractItems($params)
    {
        try {
            if (!isset($params['custom_sku_list'])){
                throw new \Exception('未给定商品明细！');
            }
            $params['custom_sku_list'] = json_decode($params['custom_sku_list'], true);
            $customSkuArray = array_column($params['custom_sku_list'], 'custom_sku_list');
            $customSkuList = [];
            foreach ($customSkuArray as $item){
                $customSkuList = array_merge($customSkuList, $item);
            }
            $spuList = [];
            $sizeArr = []; // 保存尺码
            $sizeList = []; // 动态尺码表头 id => name
            $spuSort = [];
            $colorKey = [];
            foreach ($customSkuList as $v){
                if (!isset($sizeArr[$v['size']])){
                    $sizeArr[] = $v['size'];
                    $sizeList[$v['size']] = $v['size'];
                }
            }
            $spuArr = $params['custom_sku_list'];
            $suppliers   = DB::table('suppliers')->select(['id', 'name', 'supplier_no'])->get()->pluck('name', 'id');
//            foreach ($spuArr as $item){
//                $key = $item['order_id'].'-'.$item['spu_id'].'-'.$item['color_identifying'];
//                if (isset($spuList[$key])){
//                    if (isset($spuList[$key][$item['size']])){
//                        $spuList[$key][$item['size']] += $item['not_contracted_num'];
//                        $spuList[$key][$item['size'].'_max_num'] += $item['not_contracted_num'];
//                        $spuList[$key]['size_num'][$item['size']] += $item['not_contracted_num'];
//                        $spuList[$key]['size_max_num'][$item['size']] += $item['not_contracted_num'];
//                        $spuList[$key]['order_num'] += $item['order_num'];
//                        $spuList[$key]['custom_sku_list'][] = $item;
//                    }
//                }else{
//                    $spuList[$key] = [
//                        'id' => $item['order_id'].'-'.$item['spu_id'].'-'.$item['color_identifying'],
//                        'order_id' => $item['order_id'],
//                        'spu_id' => $item['spu_id'],
//                        'spu' => $item['spu'],
//                        'color_name' => $item['color_name'],
//                        'color_identifying' => $item['color_identifying'],
//                        'color_name_en' => $item['color_name_en'],
//                        'order_num' => $item['order_num'],
//                        'name' => $item['name_en'],
//                        'price' => $item['price'],
//                        'img' => $item['img'],
//                        'custom_sku_list' => [$item],
//                        'suppliers_id'      => $item['suppliers_id'],
//                        'suppliers_name'    => isset($suppliers[$item['suppliers_id']]) ? $suppliers[$item['suppliers_id']] : '',
//                    ];
//                    $colorKey[] = $item['spu_id'].'-'.$item['color_identifying'];
//                    foreach ($sizeArr as $size){
//                        if (!isset($spuList[$key][$size])){
//                            $spuList[$key][$size] = 0;
//                            $spuList[$key][$size.'_max_num'] = 0;
//                            $spuList[$key]['size_num'][$size] = 0;
//                            $spuList[$key]['size_rule'][] = $size;
//                            $spuList[$key]['size_max_num'][$size] = 0;
//                        }
//                    }
//                    if (isset($spuList[$key][$item['size']])){
//                        $spuList[$key][$item['size']] += $item['not_contracted_num'];
//                        $spuList[$key][$item['size'].'_max_num'] += $item['not_contracted_num'];
//                        $spuList[$key]['size_num'][$item['size']] += $item['not_contracted_num'];
//                        $spuList[$key]['size_max_num'][$item['size']] += $item['not_contracted_num'];
//                    }
//                }
//            }
            foreach ($spuArr as &$item){
                $item['size_rule'] = $sizeArr;
                $sizeNum = [];
                $sizeMaxNum = [];
                foreach ($sizeArr as $size){
                    $sizeNum[$size] = $item['size_num'][$size] ?? 0;
                    $sizeMaxNum[$size] = $item['size_num'][$size] ?? 0;
                }
                $item['size_num'] = $sizeNum;
                $item['size_max_num'] = $sizeMaxNum;
                $spuList[] = $item;
            }

//            array_multisort($spuList,SORT_ASC,$colorKey);
            foreach ($spuList as $list){
                $key = $list['spu_id'].'-'.$list['color_identifying'];
                $spuSort[$key][] = $list;
            }
            $arr = [];
            foreach ($spuSort as $v){
                foreach ($v as $_v){
                    $arr[] = $_v;
                }
            }

            $spuList = array_values($arr);

            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['size_list' => $sizeList, 'count' => count($spuList), 'list' => $spuList]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getContractPdfPath($params)
    {
        try {
            if (!isset($params['contract_no']) && !isset($params['id'])){
                throw new \Exception('未给定合同标识！');
            }
//            if (!isset($params['token'])){
//                throw new \Exception('未给定令牌！');
//            }
//            $user = db::table('users')->where('token', $params['token'])->first();
//            if (empty($user)){
//                throw new \Exception('用户登录信息不存在！');
//            }
            if (!isset($params['print_type'])){
                throw new \Exception('未给定打印合同范本类型！');
            }
            $contractMdl = db::table('cloudhouse_contract_total');
            if (isset($params['contract_no'])){
                $contractMdl = $contractMdl->where('contract_no', $params['contract_no']);
            }
            if (isset($params['id'])){
                $contractMdl = $contractMdl->where('id', $params['id']);
            }
            $contractMdl = $contractMdl->first();
//            if (!in_array($contractMdl->contract_status , [2])){
//                throw new \Exception('合同未审批通过，不可打印！');
//            }
            $path = json_decode($contractMdl->pdf_file, true);
            $filePath = $path[$params['print_type']] ?? '';
            if (empty($filePath)){
                throw new \Exception('该范本类型无打印文件！');
            }
            if (isset($params['is_print_pdf']) && $params['is_print_pdf'] == 1){
                db::table('cloudhouse_contract_total')
                    ->where('id', $contractMdl->id)
                    ->update(['is_print_pdf' => 1]);
            }
            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['path' => $filePath.'?id='.rand(1, 999999)]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function batchUpdateContractPdf($params)
    {
        try {
            if (!isset($params['id']) || !is_array($params['id'])){
                throw new \Exception('未给定合同标识！');
            }
            if (!isset($params['token'])){
                throw new \Exception('未给定令牌！');
            }
            $user = db::table('users')->where('token', $params['token'])->first();
            if (empty($user)){
                throw new \Exception('当前登录用户令牌不正确！');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('id', $params['id'])
                ->get();
            if ($contractMdl->isEmpty()){
                throw new \Exception('未查询到合同数据！');
            }
            $job = new SaveContractPdfController();
            foreach ($contractMdl as $item){
                $contractNo = $item->contract_no;
                if (empty($contractNo)){
                    continue;
                }
                // 合同打印加入队列
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-服装范本（不含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 1,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-铁艺范本（不含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 2,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-服装范本（含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 3,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-铁艺范本（含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 4,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-卖单现货范本（不含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 5,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-卖单现货范本（含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 6,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-众拓范本（不含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 7,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
                $data = [
                    'title' => '购销合同'.$contractNo,
                    'type' => '购销合同-众拓范本（含税）-打印',
                    'user_id' => $user->Id,
                    'print_type' => 8,
                    'contract_no' => $contractNo
                ];
                $job::runJob($data);
            }
            $time = count($params['id']) * 2;
            return ['code' => 200, 'msg' => '批量更新打印文件成功！预估需要等待'.$time.'分钟！'];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '批量更新打印文件失败！'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function uploadContractFile($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id']))
            {
                throw new \Exception('未给定合同标识！');
            }
            if (!isset($params['file']) || !is_array($params['file']) || empty($params['file'])){
                throw new \Exception('未给定上传文件|上传文件格式不正确|上传文件为空！');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->where('id', $params['id'])
                ->first();
            if (empty($contractMdl)){
                throw new \Exception('合同数据不存在！');
            }
            $update = db::table('cloudhouse_contract_total')
                ->where('id', $params['id'])
                ->update(['file' => json_encode($params['file'])]);
            if (empty($update)){
                throw new \Exception('数据更新失败！');
            }
            $cloudhouse = new \App\Models\CloudHouse();
            $to = $cloudhouse->ConcactToOneDog(['contract_no'=>$contractMdl->contract_no]);

            return ['code' => 200, 'msg' => '上传成功！','data'=>$to];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '上传失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getOrderReportForms($params)
    {
        $list = db::table('amazon_place_order_task')
            ->where('status', '>=', 2);

        if (isset($params['contract_no'])){
            $contractMdl = db::table('cloudhouse_contract_total')
                ->where('contract_no', 'like', '%'.$params['contract_no'].'%')
                ->get()
                ->toArrayList();
            $orderIds = [];
            foreach ($contractMdl as $c)
            {
                if($c['bind_place_ids']){
                    $id = explode(',', $c['bind_place_ids']);
                    $orderIds = array_merge($orderIds, $id);
                }
            }
            $list = $list->whereIn('id', $orderIds);
        }

        if (isset($params['status']) && is_array($params['status'])){
            $list = $list->whereIn('status', $params['status']);
        }

        if (isset($params['order_id'])){
            $list = $list->where('id', $params['order_id']);
        }

        if (isset($params['user_id'])){
            $list = $list->where('user_id', $params['user_id']);
        }

        if (isset($params['platform_id'])){
            $list = $list->where('platform_id', $params['platform_id']);
        }

        if (isset($params['custom_sku'])){
            $customSkuMdl = db::table('self_custom_sku')
                ->where('custom_sku', 'like', '%'.$params['custom_sku'].'%')
                ->orWhere('old_custom_sku', 'like', '%'.$params['custom_sku'].'%')
                ->get()
                ->toArrayList();
            $customSkuIds = array_column($customSkuMdl, 'id');
            $orderDetailMdl = db::table('amazon_place_order_detail')
                ->whereIn('custom_sku_id', $customSkuIds)
                ->get()
                ->toArrayList();
            $orderIds = array_column($orderDetailMdl, 'order_id');
            $list = $list->whereIn('id', $orderIds);
        }

        if (isset($params['spu'])){
            $spuMdl = db::table('self_spu')
                ->where('spu', 'like', '%'.$params['spu'].'%')
                ->orWhere('old_spu', 'like', '%'.$params['spu'].'%')
                ->get()
                ->toArrayList();
            $spuIds = array_column($spuMdl, 'id');
            $orderDetailMdl = db::table('amazon_place_order_detail')
                ->whereIn('spu_id', $spuIds)
                ->get()
                ->toArrayList();
            $orderIds = array_column($orderDetailMdl, 'order_id');
            $list = $list->whereIn('id', $orderIds);
        }

        if (isset($params['color_id']) && is_array($params['color_id'])){
            $customSkuMdl = db::table('self_custom_sku')
                ->whereIn('color_id', $params['color_id'])
                ->get()
                ->toArrayList();
            $customSkuIds = array_column($customSkuMdl, 'id');
            $orderDetailMdl = db::table('amazon_place_order_detail')
                ->whereIn('custom_sku_id', $customSkuIds)
                ->get()
                ->toArrayList();
            $orderIds = array_column($orderDetailMdl, 'order_id');
            $list = $list->whereIn('id', $orderIds);
        }

        $count = $list->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }

        $list = $list->orderBy('creattime', 'DESC')
            ->get();

        $orderDetailMdl = db::table('amazon_place_order_detail')
            ->get();
        $orderDetailNum = [];
        foreach ($orderDetailMdl as $detail)
        {
            $orderNum = array_sum(json_decode($detail->order_num, true));
            if (isset($orderDetailNum[$detail->order_id])){
                $orderDetailNum[$detail->order_id] += $orderNum;
            }else{
                $orderDetailNum[$detail->order_id] = $orderNum;
            }
        }

        $contractMdl = db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
            ->get(['a.*', 'b.report_date', 'b.total_count']);
        $contractList = [];
        $orderContractDetail = [];
        foreach ($contractMdl as $contract){
            $contractList[$contract->contract_no] = $contract;
            if (isset($orderContractDetail[$contract->order_id][$contract->contract_no])){
                $orderContractDetail[$contract->order_id][$contract->contract_no]['contract_num'] += $contract->count;
            }else{
                $orderContractDetail[$contract->order_id][$contract->contract_no] = [
                    'contract_no' => $contract->contract_no,
                    'contract_num' => $contract->count,
                    'report_date' => $contract->report_date,
                    'contract_total_count' => $contract->total_count,
                ];
            }
        }

        $orderContractList = [];
        $orderContractNum = [];
        $orderContractTotalNum = [];
        $orderContractNumRatio = [];
        foreach ($orderContractDetail as $orderId => $detail){
            $orderContractList[$orderId] = array_column($detail, 'contract_no');
            $orderContractNum[$orderId] = array_sum(array_column($detail, 'contract_num'));
            $orderContractTotalNum[$orderId] = array_sum(array_column($detail, 'contract_total_count'));
//            var_dump(array_sum(array_column($detail, 'contract_num')).' / '.array_sum(array_column($detail, 'contract_total_count')));
            if ($orderContractTotalNum[$orderId] > 0){
                $orderContractNumRatio[$orderId] = bcdiv($orderContractNum[$orderId], $orderContractTotalNum[$orderId], 8);
            }
        }

        $contractPlanMdl = db::table('cloudhouse_contract_plan')
            ->get();
        $contractPlan = [];
        $contractPlanTotal = [];
        foreach ($contractPlanMdl as $v){
            $v->plan_time = date('Y-m-d', strtotime($v->plan_start_time)).' - '.date('Y-m-d', strtotime($v->plan_end_time));
            $contractPlan[$v->contract_no][] = $v;
            if (isset($contractPlanTotal[$v->contract_no])){
                $contractPlanTotal[$v->contract_no]['num'] += $v->num;
            }else{
                $contractPlanTotal[$v->contract_no] = [
                    'contract_no' => $v->contract_no,
                    'num' => $v->num,
                ];
            }
        }

        $contractPlanList = [];
        $contractPlanTotalList = [];
        foreach ($orderContractList as $orderId => $contractNoList){
            foreach ($contractNoList as $contractNo){
                if (!isset($contractPlan[$contractNo])){
                    continue;
                }
//                if (isset($contractPlanList[$orderId])){
//                    $contractPlanList[$orderId] = array_merge($contractPlanList[$orderId], $contractPlan[$contractNo]);
//                }else{
//                    $contractPlanList[$orderId] = $contractPlan[$contractNo];
//                }
                $contractPlanList[$orderId][$contractNo] = $contractPlan[$contractNo];

                if (!isset($contractPlanTotal[$contractNo])){
                    continue;
                }
//                if (isset($contractPlanTotalList[$orderId])){
//
//                }else{
//                    $contractPlanTotalList[$orderId] = $contractPlanTotal[$contractNo];
//                }
                $contractPlanTotalList[$orderId][] = $contractPlanTotal[$contractNo];
            }
        }

        $goodsTransfersDetail = db::table('goods_transfers_detail as a')
            ->leftJoin('goods_transfers as b', 'a.order_no', '=', 'b.order_no')
            ->whereIn('b.type_detail', [2, 9])
            ->whereIn('b.is_push', [1, 2, 4])
            ->get(['a.*', 'b.type_detail', 'b.is_push', 'b.platform_id', 'b.in_house', 'b.delivery_time', 'b.sj_arrive_time',
                'b.push_time'
            ]);
        $inHouseList = [];
        $outHouseList = [];
        foreach ($goodsTransfersDetail as $g){
            if ($g->type_detail == 2){
                $inHouseList[] = $g;
            }
            if ($g->type_detail == 9){
                $outHouseList[] = $g;
            }
        }
        $orderInHouseList = [];
        $orderOutHouseList = [];
        foreach ($orderContractList as $orderId => $contractList){
            foreach ($inHouseList as $g){
                if (in_array($g->contract_no, $contractList)){
                    $orderInHouseList[$orderId][] = $g;
                }
            }
            foreach ($outHouseList as $g){
                if (in_array($g->contract_no, $contractList)){
                    $orderOutHouseList[$orderId][] = $g;
                }
            }
        }
        $orderShipmentDetail = [];
        $orderShipmentNum = [];
        $orderWaitHouseNum = [];
        $orderHouseNum = [];
        $warehouseMdl = db::table('cloudhouse_warehouse')
            ->get(['id', 'warehouse_name'])
            ->pluck('warehouse_name', 'id');
        foreach ($orderInHouseList as $orderId => $detail){
            foreach ($detail as $d){
                $transfers_num = round(bcmul($d->transfers_num, $orderContractNumRatio[$orderId] ?? 1, 4));
                $receive_num = round(bcmul($d->receive_num, $orderContractNumRatio[$orderId] ?? 1, 4));
                $wait_house_num = bcsub($transfers_num, $receive_num);
                if (isset($orderShipmentNum[$orderId])){
                    $orderShipmentNum[$orderId] += $transfers_num;
                }else{
                    $orderShipmentNum[$orderId] = $transfers_num;
                }
                if (isset($orderHouseNum[$orderId])){
                    $orderHouseNum[$orderId] += $receive_num;
                }else{
                    $orderHouseNum[$orderId] = $receive_num;
                }
                if (isset($orderWaitHouseNum[$orderId])){
                    $orderWaitHouseNum[$orderId] += $wait_house_num;
                }else{
                    $orderWaitHouseNum[$orderId] = $wait_house_num;
                }
                if (isset($orderShipmentDetail[$orderId][$d->order_no])){
                    $orderShipmentDetail[$orderId][$d->order_no]['transfers_num'] += $transfers_num;
                    $orderShipmentDetail[$orderId][$d->order_no]['receive_num'] += $receive_num;
                    $orderShipmentDetail[$orderId][$d->order_no]['wait_house_num'] += $wait_house_num;
                }else{
                    $orderShipmentDetail[$orderId][$d->order_no] = [
                        'order_no' => $d->order_no,
                        'in_house_name' => $warehouseMdl[$d->in_house] ?? '未知仓库',
                        'transfers_num' => $transfers_num,
                        'receive_num' => $receive_num,
                        'wait_house_num' => $wait_house_num,
                        'sj_arrive_time' => $d->sj_arrive_time,
                        'delivery_time' => $d->delivery_time,
                        'type_detail' => $d->type_detail,
                        'push_time' => $d->push_time,
                    ];
                }
            }
        }

        $orderOutHouseShipmentDetail = [];
        $orderOutHouseShipmentNum = [];
        $orderOutHouseWaitHouseNum = [];
        $orderOutHouseNum = [];
        foreach ($orderOutHouseList as $orderId => $detail){
            foreach ($detail as $d){
                $transfers_num = round(bcmul($d->transfers_num, $orderContractNumRatio[$orderId] ?? 1, 4));
                $receive_num = round(bcmul($d->receive_num, $orderContractNumRatio[$orderId] ?? 1, 4));
                $wait_house_num = bcsub($transfers_num, $receive_num);
                if (isset($orderOutHouseShipmentNum[$orderId])){
                    $orderOutHouseShipmentNum[$orderId] +=$transfers_num;
                }else{
                    $orderOutHouseShipmentNum[$orderId] =$transfers_num;
                }
                if (isset($orderOutHouseNum[$orderId])){
                    $orderOutHouseNum[$orderId] += $receive_num;
                }else{
                    $orderOutHouseNum[$orderId] = $receive_num;
                }
                if (isset($orderOutHouseWaitHouseNum[$orderId])){
                    $orderOutHouseWaitHouseNum[$orderId] += $wait_house_num;
                }else{
                    $orderOutHouseWaitHouseNum[$orderId] = $wait_house_num;
                }
                if (isset($orderOutHouseShipmentDetail[$orderId][$d->order_no])){
                    $orderOutHouseShipmentDetail[$orderId][$d->order_no]['transfers_num'] +=$transfers_num;
                    $orderOutHouseShipmentDetail[$orderId][$d->order_no]['receive_num'] += $receive_num;
                    $orderOutHouseShipmentDetail[$orderId][$d->order_no]['wait_house_num'] += $wait_house_num;
                }else{
                    $orderOutHouseShipmentDetail[$orderId][$d->order_no] = [
                        'order_no' => $d->order_no,
                        'in_house_name' => $warehouseMdl[$d->in_house] ?? '未知仓库',
                        'transfers_num' =>$transfers_num,
                        'receive_num' => $receive_num,
                        'wait_house_num' => $wait_house_num,
                        'sj_arrive_time' => $d->sj_arrive_time,
                        'delivery_time' => $d->delivery_time,
                        'push_time' => $d->push_time,
                    ];
                }
            }
        }
        $userMdl = db::table('users')
            ->get()
            ->keyBy('Id');
        $platformMdl = db::table('platform')
            ->get()
            ->keyBy('Id');
        foreach ($list as $v){
            $v->status_name = Constant::AMAZON_PLACE_ORDER_TASK_STATUS[$v->status] ?? '';
            $v->is_contracted_num = $orderContractNum[$v->id] ?? 0; // 已开合同数量
            $v->total_order_num = $orderDetailNum[$v->id] ?? 0; // 订单总数
            $v->not_contracted_num = bcsub($v->total_order_num, $v->is_contracted_num); // 未开合同数量
            $v->contract_no_detail = array_values($orderContractDetail[$v->id] ?? []); // 合同数量详情
            $v->shipment_detail = array_values($orderShipmentDetail[$v->id]?? []); // 出货详情
            $v->shipment_num = $orderShipmentNum[$v->id] ?? 0; // 已出货数量
            $v->contract_no = $orderContractList[$v->id] ?? []; // 合同号
            $v->not_shipment_num = bcsub($v->is_contracted_num, $v->shipment_num); // 未出货数量
            $v->wait_house_num = $orderWaitHouseNum[$v->id] ?? 0; // 待入库数量
            $v->is_house_num = $orderHouseNum[$v->id] ?? 0; // 已入库数量
            $v->return_wait_house_num = $orderOutHouseWaitHouseNum[$v->id] ?? 0; // 退回待出库库数量
            $v->return_is_house_num = $orderOutHouseNum[$v->id] ?? 0; // 退回已出库数量
            $v->user_name = $userMdl[$v->user_id]->account ?? '';
            $v->platform_name = $platformMdl[$v->platform_id]->name ?? '';
            $v->contract_plan_detail = $contractPlanList[$v->id] ?? [];
            $v->contract_plan = $contractPlanTotalList[$v->id] ?? [];
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }

    public function getContractReportForms($params)
    {
        $list = db::table('cloudhouse_contract_total');

        if (isset($params['contract_no'])){
            $list = $list->where('contract_no', 'like', '%'.$params['contract_no'].'%');
        }

        if (isset($params['maker_id'])){
            $list = $list->where('maker_id', $params['maker_id']);
        }

        if (isset($params['input_user_id'])){
            $list = $list->where('input_user_id', $params['input_user_id']);
        }

        if (isset($params['custom_sku'])){
            $customSkuMdl = db::table('self_custom_sku')
                ->where('custom_sku', 'like', '%'.$params['custom_sku'].'%')
                ->orWhere('old_custom_sku', 'like', '%'.$params['custom_sku'].'%')
                ->get()
                ->toArrayList();
            $customSkuIds = array_column($customSkuMdl, 'id');
            $contractSkuMdl = db::table('cloudhouse_custom_sku')
                ->whereIn('custom_sku_id', $customSkuIds)
                ->get()
                ->toArrayList();
            $contractNos = array_column($contractSkuMdl, 'contract_no');
            $list = $list->whereIn('contract_no', $contractNos);
        }

        if (isset($params['spu'])){
            $spuMdl = db::table('self_spu')
                ->where('spu', 'like', '%'.$params['spu'].'%')
                ->orWhere('old_spu', 'like', '%'.$params['spu'].'%')
                ->get()
                ->toArrayList();
            $spuIds = array_column($spuMdl, 'id');
            $contractSkuMdl = db::table('cloudhouse_custom_sku')
                ->whereIn('spu_id', $spuIds)
                ->get()
                ->toArrayList();
            $contractNos = array_column($contractSkuMdl, 'contract_no');
            $list = $list->whereIn('contract_no', $contractNos);
        }

        if (isset($params['color_id']) && is_array($params['color_id'])){
            $customSkuMdl = db::table('self_custom_sku')
                ->whereIn('color_id', $params['color_id'])
                ->get()
                ->toArrayList();
            $customSkuIds = array_column($customSkuMdl, 'id');
            $contractSkuMdl = db::table('cloudhouse_custom_sku')
                ->whereIn('custom_sku_id', $customSkuIds)
                ->get()
                ->toArrayList();
            $contractNos = array_column($contractSkuMdl, 'contract_no');
            $list = $list->whereIn('contract_no', $contractNos);
        }

        $count = $list->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }

        $list = $list
            ->orderBy('report_date', 'desc')
            ->get();

        $contractSkuMdl = db::table('cloudhouse_custom_sku')
            ->get();

        $contractSkuList = [];
        foreach ($contractSkuMdl as $sku){
            $contractSkuList[$sku->contract_no][] = $sku;
        }
        $goodsTransfersDetailMdl =  db::table('goods_transfers_detail as a')
            ->leftJoin('goods_transfers as b', 'a.order_no', '=', 'b.order_no')
            ->leftJoin('platform as c', 'b.platform_id', '=', 'c.Id')
            ->whereIn('b.type_detail', [2, 9])
            ->whereIn('b.is_push', [1, 2, 4])
            ->get(['a.*', 'b.type_detail', 'b.is_push', 'c.name as platform_name', 'b.in_house', 'b.delivery_time', 'b.sj_arrive_time', 'b.push_time'
            ]);
        $inHouseList = [];
        $outHouseList = [];
        $warehouseMdl = db::table('cloudhouse_warehouse')
            ->get(['id', 'warehouse_name'])
            ->pluck('warehouse_name', 'id');
        foreach ($goodsTransfersDetailMdl as $g){
            $g->in_house_name = $warehouseMdl[$g->in_house] ?? '未知仓库';
            if ($g->type_detail == 2){
                $inHouseList[] = $g;
            }
            if ($g->type_detail == 9){
                $outHouseList[] = $g;
            }
        }

        $inHouseShipmentList = [];
        foreach ($inHouseList as $i){
            $transfers_num = $i->transfers_num;
            $receive_num = $i->receive_num;
            $wait_house_num = bcsub($i->transfers_num, $i->receive_num);
            if (isset($inHouseShipmentList[$i->contract_no][$i->order_no])){
                $inHouseShipmentList[$i->contract_no][$i->order_no]['transfers_num'] += $transfers_num;
                $inHouseShipmentList[$i->contract_no][$i->order_no]['receive_num'] += $receive_num;
                $inHouseShipmentList[$i->contract_no][$i->order_no]['wait_house_num'] += $wait_house_num;
            }else{
                $inHouseShipmentList[$i->contract_no][$i->order_no] = [
                    'order_no' => $i->order_no,
                    'in_house_name' => $warehouseMdl[$i->in_house] ?? '未知仓库',
                    'transfers_num' =>$transfers_num,
                    'receive_num' => $receive_num,
                    'wait_house_num' => $wait_house_num,
                    'sj_arrive_time' => $i->sj_arrive_time,
                    'delivery_time' => $i->delivery_time,
                    'push_time' => $i->push_time,
                ];
            }
        }
        $outHouseShipmentList = [];
        foreach ($outHouseList as $i){
            $transfers_num = $i->transfers_num;
            $receive_num = $i->receive_num;
            $wait_house_num = bcsub($i->transfers_num, $i->receive_num);
            if (isset($outHouseShipmentList[$i->contract_no][$i->order_no])){
                $outHouseShipmentList[$i->contract_no][$i->order_no]['transfers_num'] += $transfers_num;
                $outHouseShipmentList[$i->contract_no][$i->order_no]['receive_num'] += $receive_num;
                $outHouseShipmentList[$i->contract_no][$i->order_no]['wait_house_num'] += $wait_house_num;
            }else{
                $outHouseShipmentList[$i->contract_no][$i->order_no] = [
                    'order_no' => $i->order_no,
                    'in_house_name' => $warehouseMdl[$i->in_house] ?? '未知仓库',
                    'transfers_num' =>$transfers_num,
                    'receive_num' => $receive_num,
                    'wait_house_num' => $wait_house_num,
                    'sj_arrive_time' => $i->sj_arrive_time,
                    'delivery_time' => $i->delivery_time,
                    'push_time' => $i->push_time
                ];
            }
        }
        $userMdl = db::table('users')
            ->get()
            ->keyBy('Id');

        $contractPlanMdl = db::table('cloudhouse_contract_plan')
            ->get();
        $contractPlan = [];
        $contractPlanTotal = [];
        foreach ($contractPlanMdl as $v){
            $v->plan_time = date('Y-m-d', strtotime($v->plan_start_time)).' - '.date('Y-m-d', strtotime($v->plan_end_time));
            $contractPlan[$v->contract_no][$v->contract_no][] = $v;
            if (isset($contractPlanTotal[$v->contract_no])){
                $contractPlanTotal[$v->contract_no]['num'] += $v->num;
            }else{
                $contractPlanTotal[$v->contract_no] = [
                    'contract_no' => $v->contract_no,
                    'num' => $v->num
                ];
            }
        }
        foreach ($list as $v){
            $v->contract_class_name = Constant::CONTRACT_CLASS[$v->contract_class] ?? '';
            $v->contract_status_name = Constant::CONTRACT_STATUS[$v->contract_status] ?? '';
            $inShipmentDetail = array_values($inHouseShipmentList[$v->contract_no] ?? []);
            $outShipmentDetail = array_values($outShipmentDetail[$v->contract_no] ?? []);
            $v->in_shipment_detail = $inShipmentDetail;
            $v->out_shipment_detail = $outShipmentDetail;
            $inHouseShipmentNum = array_sum(array_column($inShipmentDetail, 'transfers_num'));
            $inHouseNum = array_sum(array_column($inShipmentDetail, 'receive_num'));
            $inHouseWaitNum = bcsub($inHouseShipmentNum, $inHouseNum);
            $v->shipment_num = $inHouseShipmentNum; // 已出货数量
            $v->not_shipment_num = bcsub($v->total_count, $v->shipment_num); // 未出货数量
            $v->wait_house_num = $inHouseWaitNum; // 待入库数量
            $v->is_house_num = $inHouseNum; // 已入库数量
            $outHouseShipmentNum = array_sum(array_column($outShipmentDetail, 'transfers_num'));
            $outHouseNum = array_sum(array_column($outShipmentDetail, 'receive_num'));
            $outHouseWaitNum = bcsub($outHouseShipmentNum, $outHouseNum);
            $v->return_wait_house_num = $outHouseWaitNum; // 退回待出库库数量
            $v->return_is_house_num = $outHouseNum; // 退回已出库数量
            $v->input_user_name = $userMdl[$v->input_user_id]->account ?? '';
            $v->maker_name = $userMdl[$v->maker_id]->account ?? '';
            $v->contract_plan_detail = $contractPlan[$v->contract_no] ?? [];
            $v->contract_plan = [$contractPlanTotal[$v->contract_no] ?? []] ?? [];
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }

    public function getContractPlanList($params)
    {
        $list = db::table('cloudhouse_contract_plan as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no');

        if (isset($params['contract_no'])){
            $list = $list->where('a.contract_no', 'like', '%'.$params['contract_no'].'%');
        }

        if (isset($params['warehoude_id'])){
            $list = $list->where('a.warehoude_id', $params['warehoude_id']);
        }

        if (isset($params['warehoude_id'])){
            $list = $list->where('a.warehoude_id', $params['warehoude_id']);
        }

        if (isset($params['created_at']) && is_array($params['created_at'])){
            $list = $list->whereBetween('a.addtime', $params['created_at']);
        }

        if (isset($params['plan_time']) && is_array($params['plan_time'])){
            $list = $list->where('a.plan_start_time', '>', $params['plan_time'][1])
                ->orWhere('a.plan_end_time', '<', $params['plan_time'][0]);
        }

//        if (isset($params['plan_end_time']) && is_array($params['plan_end_time'])){
//            $list = $list->whereBetween('a.plan_end_time', $params['plan_end_time']);
//        }

        $count = $list->count();

        $supplierMdl = db::table('suppliers')
            ->get()
            ->keyBy('Id');



        if ((isset($params['limit']) || isset($params['page'])) && (!isset($params['post_type']) || $params['post_type'] != 2)){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }

        $list = $list->orderBy('a.addtime', 'desc')
            ->select('a.*', 'b.supplier_id')
            ->get();
        $warehouseMdl = db::table('cloudhouse_warehouse')
            ->get(['id', 'warehouse_name'])
            ->pluck('warehouse_name', 'id');
        $userMdl = db::table('users')
            ->get(['Id', 'account'])
            ->pluck('account', 'Id');
        foreach($list as $v){
            $v->supplier_no = $supplierMdl[$v->supplier_id]->supplier_no ?? '';
            $v->plan_time = date('Y-m-d', strtotime($v->plan_start_time)).' ~ '. date('Y-m-d', strtotime($v->plan_end_time));
            $v->status_name = Constant::CONTRACT_PLAN_STATUS[$v->status] ?? '';
            $v->warehouse_name = $warehouseMdl[$v->warehouse_id] ?? '未知仓库';
            $v->audit_name = $userMdl[$v->audit_id] ?? '';
            $v->create_name = $userMdl[$v->created_id] ?? '';
        }

        if (isset($params['post_type']) && $params['post_type'] == 2){
            $data = $list;

            $p['title']='合同到货计划表'.time();
            $title = [
                'warehouse_name'  => '仓库',
                'contract_no'  => '合同号',
                'status_name'  => '状态',
                'supplier_no' => '供应商编码',
                'status_name' => 'spu',
                'box_num' => '箱数',
                'num' => '到货数量',
                'plan_time' => '计划到货时间段',
                'created_at' => '创建时间',
            ];

            $p['title_list']  = $title;
            $p['data'] =  $data;
            $userId = 1;
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $userId = $users->Id;
                    }
                }
            }
            $find_user_id = $userId;
            $p['user_id'] = $find_user_id;
            $p['type'] = '合同到货计划表导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }

    public function getContractSpuList($params)
    {
        $list = db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no');
        $data = db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no');
        if (isset($params['contract_no'])){
            $list = $list->where('a.contract_no', 'like', '%'.trim($params['contract_no']).'%');
            $data = $data->where('a.contract_no', 'like', '%'.trim($params['contract_no']).'%');
        }

        if (isset($params['spu'])){
            $spuMdl = db::table('self_spu')
                ->where('spu', 'like', '%'.trim($params['spu']).'%')
                ->orWhere('old_spu', 'like', '%'.trim($params['spu']).'%')
                ->get(['id'])
                ->toArrayList();
            $spuIds = array_column($spuMdl, 'id');
            $list = $list->whereIn('a.spu_id', $spuIds);
            $data = $data->whereIn('a.spu_id', $spuIds);
        }

        if (isset($params['spu'])){
            $list = $list->where('a.spu', 'like', '%'.trim($params['spu']).'%');
            $data = $data->where('a.spu', 'like', '%'.trim($params['spu']).'%');
        }

        if (isset($params['report_date']) && is_array($params['report_date'])){
            $list = $list->whereBetween('a.report_date', $params['report_date']);
            $data = $data->whereBetween('a.report_date', $params['report_date']);
        }

        if (isset($params['contract_class']) && is_array($params['contract_class'])){
            $list = $list->whereIn('b.contract_class', $params['contract_class']);
            $data = $data->whereBetween('a.report_date', $params['report_date']);
        }

        if (isset($params['supplier_id'])){
            $list = $list->where('b.supplier_id', $params['supplier_id']);
            $data = $data->whereBetween('a.report_date', $params['report_date']);
        }

        $count = $list->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }
        $controller = new Controller();
        $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['show_all_contract']]);

        $list = $list->orderBy('b.create_time', 'desc')
            ->select('a.*', 'b.supplier_short_name', 'b.maker_id', 'b.create_time', 'b.input_user_id', 'b.contract_class', 'b.contract_status')
            ->get();

        $userMdl = db::table('users')
            ->get()
            ->keyBy('Id');
        foreach ($list as $v){
            $v->contract_class_name = Constant::CONTRACT_CLASS[$v->contract_class] ?? '艾诺科合同';
            $v->contract_status_name = Constant::CONTRACT_STATUS[$v->contract_status] ?? '';
            $v->maker_name = $userMdl[$v->maker_id]->account ?? '';
            $v->input_user_name = $userMdl[$v->input_user_id]->account ?? '';
            $v->supplier_name = $v->supplier_short_name;
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }

    public function downloadContractExcel($params)
    {
        try {
            if (isset($params['token'])){
                $user = db::table('users')->where('token', $params['token'])
                    ->first();
                if (empty($user)){
                    throw new \Exception('未查询到操作人信息！');
                }
                $params['user_id'] = $user->Id;
            }else{
                throw new \Exception('未给定操作人令牌！');
            }
            if (isset($params['id']) && !empty($params['id'])) {
                $contractMdl = DB::table('cloudhouse_contract_total')->where('id', $params['id'])
                    ->first();
                if (empty($contractMdl)) {
                    throw new \Exception('未查询到该合同信息！');
                }
            } else {
                throw new \Exception('未给定合同标识！');
            }
            $contractModel = new AmazonPlaceOrderContractModel();
            $contractDetail = $contractModel->getAmazonPlaceOrderContractDetail(['contract_no' => $contractMdl->contract_no])['data'] ?? [];
            $rule = [];
            foreach ($contractDetail->custom_sku_items as $cus_item){
                $rule[] = $cus_item['size'];
            }
            $rule = array_unique($rule);
            $length = count($rule);
            $width = 9 - $length;
            $priceWidth = 1;
            $memoWidth = 1;
            if ($width > 2){
                if ($width%2 == 1){
                    $priceWidth = bcdiv($width, 2) + 1;
                    $memoWidth = bcdiv($width, 2);
                }
                if ($width%2 == 0){
                    $priceWidth = bcdiv($width, 2);
                    $memoWidth = bcdiv($width, 2);
                }
            }
            $baseModel = new BaseModel();
            $process_contract_no = '';
            $process_supplier_name = '';
            if ($contractDetail->contract_class == 5){
                $process_contract_no = '实际外发加工合同号：'.$contractDetail->process_contract_no;
                $process_supplier_name = '实际外发加工工厂：'.$contractDetail->process_supplier_name;
            }
            switch ($params['print_type']) {
                case 8:
                    $printType = '购销合同-众拓范本(含税)-打印';
                    $html = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            border-collapse: collapse;
        }
        td, th {
            padding: 0;
        }
        table {
            border-collapse: separate;
            border-spacing: 0;
            width: 100%;
        }
        td,tr {
            font-size: 12px;
            line-height：12px;
        }
        td{
            width: 5%;
        }
        .border1{
            border-width: 0.2rem;
            border-style: solid solid solid solid;
            border-color: black;
            min-height: 20px;
        }
        .fontBlod{
            font-weight: bold;
        }
        .cell {
            display: flex;
	        justify-content: center;
	        align-items: center;
        }
    </style>
</head>
<body>
    <table   width="100%" cellpadding="2" cellspacing="0">
        <tr>
            <td colspan="20" style="text-align: center;font-size: 20px; font-weight: bold; padding-bottom: 20px;"><div class="cell">'.$contractDetail->company_name.'购销合同</div></td>
        </tr>
        <tr>
            <td colspan="20"></td>
        </tr>
        <tr>
            <td colspan="14"><div class="cell">甲方单位：'.$contractDetail->company_name.'(需方)</div></td>
            <td colspan="6"><div class="cell">合同编号：'.$contractDetail->contract_no.'</div></td>
        </tr>
        <tr>
            <td colspan="14"><div class="cell">乙方单位：'.$contractDetail->supplier_name.'(供方)</div></td>
            <td colspan="6"><div class="cell">签约时间：'.$contractDetail->sign_date.'</div></td>
        </tr>
        <tr>
            <td colspan="14"></td>
            <td colspan="6"><div class="cell">签约地点：'.$contractDetail->signing_location.'</div></td>
        </tr>
        <tr>
            <td colspan="14"></td>
            <td colspan="6"><div class="cell">交期时间：'.$contractDetail->report_date.'</div></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: left; font-weight: bold;"><div class="cell">为促进甲方、乙方双方合作顺利开展，保障双方权益，根据《中华人民共和国民法典》及相关法律法规的规定，经双方友好协商特订立本合同，供共同遵守。</div></td>
        </tr>
        <tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>
        <tr>
            <td colspan="20"><div class="cell">一、 1、甲方商品的款号/品名，数量，单价，金额（人民币）</div></td>
        </tr>

        <tr>
        <td class="border1" colspan="3" rowspan="2" style="text-align: center;"><div class="cell">款号</div></td>
            <td class="border1" colspan="2" rowspan="2" style="text-align: center;"><div class="cell">款式</div></td>
            <td class="border1" colspan="2" rowspan="2" style="text-align: center;"><div class="cell">品名</div></td>
            <td class="border1" colspan="'.($length+1).'" rowspan="1" style="text-align: center;"><div class="cell">颜色尺码</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">合计(件/套)</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">单价(元)(含税)</div></td>
            <td class="border1" colspan="'.$priceWidth.'" rowspan="2" style="text-align: center;"><div class="cell">金额(含税)</div></td>
            <td class="border1" colspan="1" rowspan="2" style="text-align: center;"><div class="cell">吊牌</div></td>
            <td class="border1" colspan="'.$memoWidth.'" rowspan="2" style="text-align: center;"><div class="cell">备注</div></td>
        </tr>';

                    $html .= '<tr>
            <td class="border1" colspan="1" rowspan="1" style="text-align: center;">颜色</td>';

                    foreach ($rule as $size){
                        $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.$size.'</td>';
                    }

                    $html .= '
        </tr>';
                    $contractSpu = $contractDetail->spu_items;
                    $sizeInfo = [];
                    $totalPrice = 0;
                    foreach ($contractSpu as $v){
                        $html .= '<tr>
                <td class="border1" colspan="3" style="text-align: center;">'.$v['spu'].'</td>
                <td class="border1" colspan="2" style="text-align: center;"></td>
                <td class="border1" colspan="2" style="text-align: center;">'.$v['title'].'</td>
                <td class="border1" colspan="1" style="text-align: center;">'.$v['color_name'].'/'.$v['color_identifying'].'</td>';
                        $numInfo = $v['num_info'];
                        foreach ($rule as $size){
                            $num = $numInfo->$size ?? 0;
                            if (isset($sizeInfo[$size])){
                                $sizeInfo[$size] += $num;
                            }else{
                                $sizeInfo[$size] = $num;
                            }
                            $totalPrice += $v['one_price'] * $num;
                            $html .= '<td class="border1" colspan="1" style="text-align: center;">'.$num.'</td>';
                        }
                        $html .= '<td class="border1" colspan="1" rowspan="1" style="text-align: center;"><div class="cell">'.$v['count'].'</div></td>
                <td class="border1" colspan="1" rowspan="1" style="text-align: center;"><div class="cell">'.$v['one_price'].'</div></td>
                <td class="border1" colspan="'.$priceWidth.'" rowspan="1" style="text-align: center;"><div class="cell">'.$v['price'].'</div></td>
                <td class="border1" colspan="1" style="text-align: center;">'.$contractDetail->brand.'</td>
                <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;">'.$v['memo'].'</td>
            </tr>';
                    }
                    $html .= '<tr>
            <td class="border1" colspan="7" style="text-align: center;">合计金额</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>';
                    foreach ($rule as $size){
                        $num = $sizeInfo[$size] ?? 0;
                        $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.$num.'</td>';
                    }

                    $html .= '
            <td class="border1" colspan="1" style="text-align: center;">'.array_sum($sizeInfo).'</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>
            <td class="border1" colspan="'.$priceWidth.'" style="text-align: center;">'.$baseModel->floorDecimal($totalPrice).'</td>
            <td class="border1" colspan="1" style="text-align: center;"></td>
            <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;"></td>
        </tr>';
                    $payment_information = $contractDetail->payment_information;
                    $count = 4;
                    if (count($payment_information) > $count){
                        $count = count($payment_information);
                    }
                    for ($i = 0; $i<$count; $i++){
                        $title = $payment_information[$i]['title'] ?? '';
                        $money = $payment_information[$i]['money'] ?? '';
                        $html .= '<tr>
                <td class="border1" colspan="7" style="text-align: center;">'.$title.'</td>
                <td class="border1" colspan="1" style="text-align: center;"></td>';

                        foreach ($rule as $size){
                            $html .= '<td class="border1" colspan="1" style="text-align: center;"></td>';
                        }

                        $html .= '
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="'.$priceWidth.'" style="text-align: center;">'.$money.'</td>
                <td class="border1" colspan="1" style="text-align: center;"></td>
                <td class="border1" colspan="'.$memoWidth.'" style="text-align: center;"></td>
            </tr>';
                    }
                    $html .= '<tr>
            <td colspan="20" style="text-align: center;"></td>
        </tr>

        <tr>
            <td colspan="20">2、需提供产前确认样（拍照样）齐色码'.implode('、', $rule).'各一件。</td>
        </tr>

        <tr>
            <td colspan="20">3、出货良品率保持99%，按合同规定的交货期交货，若逾期大于8天以上的，以规定合同交期而产生的交期逾期，以逾期货款金额为基数按每日万分之7. 5计算违约金扣款，≥30天除了扣款还需承担甲方运费。</td>
        </tr>
        <tr>
            <td colspan="20">（如有其他原因延期交货，双方友好协商交货日期，并以书面或者邮件给以通知，须甲方同意为准，不可延期后再进行延期补签申请）。</td>
        </tr>

        <tr>
            <td colspan="20">二、质量要求技术标准、乙方对质量负责的条件:</td>
        </tr>
        <tr>
            <td colspan="20">1、产品质量和材料以需方提供的原样一致及双方最终签章确认产前样为准！如有不一致，甲方有权取消本次合同。</td>
        </tr>
        <tr>
            <td colspan="20">2、必须符合国家法定商检标准及甲方提出的质量标准,按照AQL2.5质量标准进行验货。</td>
        </tr>
        <tr>
            <td colspan="20">三、交货地点、方式及运输费用</td>
        </tr>
        <tr>
            <td colspan="20">1、须按甲方提供的交货期及指定的地点交货，我方地址分别为：厦门同安仓、泉州仓、厦门软二仓。</td>
        </tr>
        <tr>
            <td colspan="20">2、乙方按甲方指定地点送货，在保证交货期情况下乙方可自主选择运输方式，运输费用乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">四、包装标准：按我司要求包装（详细按理单资料）</td>
        </tr>
        <tr>
            <td colspan="20">五、验收标准、方法及提出异议期限：</td>
        </tr>
        <tr>
            <td colspan="20">1、甲方派出的QC以确认样和国家法定商检标准为准，对产品的品质、规格、数量、包装等外观质检验。乙方须严格按甲方要求执行。</td>
        </tr>
        <tr>
            <td colspan="20">2、 按确认样和制作单要求生产。乙方未能按质按量按时交货引起的损失，概由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">3、甲方在收货后有权对因工厂生产技术、材料等方面造成的质量问题提出索赔、严重者可提出退货及索赔，乙方应予以接受。</td>
        </tr>
        <tr>
            <td colspan="20">4、甲方需于到货后15天内进行抽验，若存在数量及质量问题的，需向乙方书面提出;逾期视为检验合格。 </td>
        </tr>
        <tr>
            <td colspan="20">5、大货只接受订单数量±3%（按各码数）。</td>
        </tr>
        <tr>
            <td colspan="20">六、货款的计算及结算方式：</td>
        </tr>
        <tr>
            <td colspan="20">1、付款方式：T/T</td>
        </tr>';

                    $html .= '
        <tr>
            <td colspan="20">'.$contractDetail->payment_settlement_method.'</td>
        </tr>';

                    $html .= '<tr>
            <td colspan="20">七、违约责任：</td>
        </tr>
        <tr>
            <td colspan="20">2、乙方所交货品与本合同规定质量不符导致甲方在转售该批服装时被客人拒绝接收或降价或其它救济方式时，甲方有权对乙方采取相应的措施，乙方不得拒绝。</td>
        </tr>
        <tr>
            <td colspan="20">3、因乙方不能按期交货，甲方不同意延期所引起的各项运费或制约款等费用由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">八、解决合同纠纷方式：</td>
        </tr>
        <tr>
            <td colspan="20">合同履行过程中若发生纠纷，经友好协商未果提起诉讼，由签约地（厦门思明区）法院管辖。</td>
        </tr>
        <tr>
            <td colspan="20">九、其它约定事项:</td>
        </tr>
        <tr>
            <td colspan="20">1、由甲方提供的理单资料（即大货要求）均为本合同附件，其它未尽事宜可经双方商定进行书面修改补充并视为本合同不可分割的部分，同样具有法律效力。</td>
        </tr>
        <tr>
            <td colspan="20">2、大货材料必须由甲方确认后才可生产，否则由此引起的责任及后果由乙方承担;</td>
        </tr>
        <tr>
            <td colspan="20">3、甲方品牌产品、组合方式、设计款式、包装方式等待均不可销售其他电商卖家。如发现乙方向其他电商卖家销售以上规定的产品造成甲方损失应由乙方承担。</td>
        </tr>
        <tr>
            <td colspan="20">4、如果是因为乙方质量等原因，造成甲方派QC前往乙方工厂验货超过2次的，所产生的验货费用由乙方承担。 （根据验货地点费用起：500元-1000元以上）</td>
        </tr>
        <tr>
            <td colspan="20">5、乙方须在交货前免费提供符合甲方质量要求的初样，修改样，产前样，大货样，若不符合要求，须重新提供。</td>
        </tr>
        <tr>
            <td colspan="20">6、乙方必须做产前样给甲方确认后，方可开裁&生产大货，否则后果将由乙方负全部责任。</td>
        </tr>
        <tr>
            <td colspan="10" rowspan="1">'.$process_contract_no.'</td>
            <td colspan="10" rowspan="1">'.$process_supplier_name.'</td>
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="20" rowspan="1"></td>
        </tr>
        <tr>
            <td colspan="2">甲方单位：</td>
            <td colspan="8">'.$contractDetail->company_name.'</td>
            <td colspan="2">乙方单位：</td>
            <td colspan="8">'.$contractDetail->supplier_name.'</td>
        </tr>
        <tr>
            <td colspan="2">地址：</td>
            <td colspan="8">'.$contractDetail->company_address.'</td>
            <td colspan="2">地址：</td>
            <td colspan="8">'.$contractDetail->supplier_address.'</td>
        </tr>
        <tr>
            <td colspan="10">甲方代表：'.$contractDetail->maker_name.'</td>
            <td colspan="10">乙方代表：</td>
        </tr>
        <tr>
            <td colspan="10">签章：</td>
            <td colspan="10">签章：</td>
        </tr>
        <tr>
            <td colspan="10">日期：'.$contractDetail->sign_date.'</td>
            <td colspan="10">日期：'.$contractDetail->sign_date.'</td>
        </tr>
    </table>
</body>
</html>';
                    break;
            }
            @ob_clean();
            $fileType = 'xlsx';
            $fileName = '合同'.$contractMdl->contract_no;
            if ($fileType == 'xlsx') {
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Cache-Control: max-age=0');
                header("Content-Type:application/vnd.ms-excel");
                header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
//                $objWriter = \PHPExcel_IOFactory::createWriter($html, 'Excel2007');
                echo $html;exit();

//                 $objWriter->save('php://output');
                $objWriter->save($path);
                $url = 'http://api.zity.cn/admin/export2/'.$fileName . '.xlsx?id='.time();
                return ['code' => 200, 'msg' => '获取成功', 'data' => ['path' => 'https://view.officeapps.live.com/op/view.aspx?src='.$url]];
            }

            return ['code' => 200, 'msg' => '打印成功！', 'data' => []];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function saveContractPaymentMethod($params)
    {
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            if (!isset($params['title']) || empty($params['title'])){
                throw new \Exception('未给定付款方式描述！');
            }

            if (!isset($params['day_num']) || $params['day_num'] < 0){
                throw new \Exception('未给定账期天数或给定的数值不正确！');
            }

            $params['contract_status'] = 0;
            if (isset($params['payment_information']) && !empty($params['payment_information'])) {
                $error = '';
                $ratio = 0;
                foreach ($params['payment_information'] as $k => &$v) {
                    if (!isset($v['bill_type']) || empty($v['bill_type'])) {
                        $error .= '请检查第' . ($k + 1) . '行款项是否设置账款类型';
                        continue;
                    } else {
                        if (!isset(Constant::BILL_TYPE[$v['bill_type']])) {
                            $error .= '请检查第' . ($k + 1) . '行款项设置的账款类型为非预设类型！';
                            continue;
                        }
                    }
                    if (!isset($v['title']) || empty($v['title'])) {
                        $error .= '请检查第' . ($k + 1) . '行款项未设置描述';
                        continue;
                    }
                    if (!isset($v['percentage'])) {
                        $error .= '请检查第' . ($k + 1) . '行款项是否设置比率';
                        continue;
                    } else {
                        if ($v['percentage'] <= 0) {
                            $error .= '请检查第' . ($k + 1) . '行款项比率数值是否正确';
                            continue;
                        }
                        $ratio += $v['percentage'];
                    }
                    if (!isset($v['title']) || empty($v['title'])) {
                        $error .= '请填写第' . ($k + 1) . '行申请事由！';
                        continue;
                    }
                }
                if ($ratio != 100) {
                    throw new \Exception('款项信息有误！合计比率不等于100%！');
                }
                if (!empty($error)){
                    throw new \Exception('款项信息有误！'.$error);
                }
            }else{
                throw new \Exception('未给定款项信息！');
            }
            db::beginTransaction();
            if (isset($params['id'])){
                $methodMdl = db::table('contract_payment_method')
                    ->where('id', $params['id'])
                    ->first();
                if (empty($methodMdl)){
                    throw new \Exception('付款方式不存在！');
                }
                $contractMdl = db::table('cloudhouse_contract_total')
                    ->where('periodic_id', $params['id'])
                    ->first();
                if (!empty($contractMdl)){
                    throw new \Exception('该付款方式已生成合同不可修改！');
                }
                $save = [
                    'title' => $params['title'],
                    'payment_information' => json_encode($params['payment_information']),
                    'day_num' => $params['day_num'],
                    'user_id' => $params['user_id'],
                    'updated_at' => date('Y-m-d H:i:s', microtime(true))
                ];
                $id = db::table('contract_payment_method')
                    ->where('id', $params['id'])
                    ->update($save);
                if (empty($id)){
                    throw new \Exception('数据无变化！');
                }
            }else{
                $save = [
                    'title' => $params['title'],
                    'payment_information' => json_encode($params['payment_information']),
                    'day_num' => $params['day_num'],
                    'user_id' => $params['user_id'],
                    'created_at' => date('Y-m-d H:i:s', microtime(true))
                ];
                $id = db::table('contract_payment_method')
                    ->insertGetId($save);
                if (empty($id)){
                    throw new \Exception('新增失败！');
                }
            }
            db::commit();
            return ['code' => 200, 'msg' => '保存成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '保存失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getContractPaymentMethod($params)
    {
        $list = db::table('contract_payment_method');

        if (isset($params['title'])){
            $list = $list->where('title', 'like', '%'.$params['title'].'%');
        }

        $count = $list->count();

        if (isset($params['page']) || isset($params['limit'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)->offset($offsetNum);
        }

        $list = $list->orderBy('created_at', 'desc')
            ->get();

        foreach ($list as $v){
            $v->payment_settlement_method = $v->title;
            $v->payment_information = json_decode($v->payment_information, true);
            foreach ($v->payment_information as $_k => $_v){
                $v->payment_information[$_k]['bill_type_name'] = Constant::BILL_TYPE[$_v['bill_type']] ?? '';
            }
            $v->user_name = $this->GetUsers($v->user_id)['account'] ?? '';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }
}